一個簡單的C共享庫的建立及Python調用此庫的方法

/*********************************************************************html

* Author  : Samsonpython

* Date    : 02/02/2015linux

* Test platform:bash

*              3.13.0-24-genericide

*              GNU bash, 4.3.11(1)-release函數

* *******************************************************************/學習

在helloworld工程中,編寫了一個簡單的兩個數值相加的程序,編譯成爲共享庫後,如何使用python對其進行調用呢?spa

使用ll命令列出當前目錄下的共享庫,其中共享庫名爲libhelloworld.so.0.0.0命令行

linuxidc@linuxidc:~/helloworld/.libs$ llorm

總用量 32

drwxr-xr-x 2 linuxidc linuxidc 4096  1月 29 14:54 ./

drwxr-xr-x 6 linuxidc linuxidc 4096  1月 29 16:08 ../

-rw-r--r-- 1 linuxidc linuxidc 3816  1月 29 14:54 helloworld.o

-rw-r--r-- 1 linuxidc linuxidc 3956  1月 29 14:54 libhelloworld.a

lrwxrwxrwx 1 linuxidc linuxidc  19  1月 29 14:54 libhelloworld.la -> ../libhelloworld.la

-rw-r--r-- 1 linuxidc linuxidc  983  1月 29 14:54 libhelloworld.lai

lrwxrwxrwx 1 linuxidc linuxidc  22  1月 29 14:54 libhelloworld.so -> libhelloworld.so.0.0.0*

lrwxrwxrwx 1 linuxidc linuxidc  22  1月 29 14:54 libhelloworld.so.0 -> libhelloworld.so.0.0.0*

-rwxr-xr-x 1 linuxidc linuxidc 9038  1月 29 14:54 libhelloworld.so.0.0.0*

進入python的命令行模式進行C語言實現的兩個數值相加的程序的調用;

linuxidc@linuxidc:~/helloworld/.libs$ python

Python 2.7.4 (default, Sep 26 2013, 03:20:56)

[GCC 4.7.3] on linux2

Type "help", "copyright", "credits" or "license" for more information.

載入ctypes類(此類便是調用C語言動態庫的方法)

>>> import ctypes

打開當前目錄的動態庫

>>> lib=ctypes.cdll.LoadLibrary("./libhelloworld.so.0.0.0")

調用動態庫中的接口

>>> lib.add(5,7)

12

兩個參數的相加的函數以下:

linuxidc@linuxidc:~/helloworld$ cat helloworld.c

#include <stdio.h>

#include <stdlib.h>

int add(int a, int b)

{

int c = a + b;

return c;

}

編譯動態庫的命令行:

gcc -shared -fPIC -DPIC helloworld.c -o libhelloworld.so.0.0.0

相關文章
相關標籤/搜索