您的位置:首页 > 编程语言 > Python开发

Python调用C库文件的两种方法

2018-01-26 15:32 232 查看

1. 使用dlopen函数调用库文件然后编译成python扩展库

1)
$ vim func.c


#include <stdio.h>

int sum(int a, int b){
printf("%d+%d=", a, b);
return a+b;
}


2)
$ gcc -o libfunc.so -shared -fPIC func.c


3)
$ vim mydlopen.c


#include <Python.h>
#include <dlfcn.h>
#include <stdio.h>
#include <time.h>
#include <string.h>

#define LIBPATH "/root/test/libfunc.so"

const int (*funcSum)(int a, int b);

static PyObject *getSum(PyObject *self, PyObject *args)
{
int a=0;
int b=0;

if (!PyArg_ParseTuple(args, "ii", &a, &b))
{
PyErr_SetString(PyExc_TypeError, "parms error");
return NULL;
}
void *handle =  dlopen(LIBPATH, RTLD_LAZY);
if (handle == NULL)
{
return NULL;
}
funcSum =  dlsym(handle,"sum");
int sum = funcSum(a, b);
return Py_BuildValue("i", sum);
}

static PyMethodDef myMethods[] = {
{"getSum", getSum, METH_VARARGS},
{NULL, NULL}
};

void initmydlopen() {
Py_InitModule("mydlopen", myMethods);
}


4)
$ vim setup.py


from distutils.core import setup, Extension
MOD = "mydlopen"
setup(name=MOD,
packages=[],
ext_modules=[Extension(MOD,
sources=["mydlopen.c"],
include_dirs=["/usr/include"],
library_dirs=["/usr/lib64"],
libraries=["dl"])])


5)
$ python setup.py install


running install
running build
running build_ext
building 'mydlopen' extension
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/include -I/usr/local/include/python2.7 -c mydlopen.c -o build/temp.linux-x86_64-2.7/mydlopen.o
mydlopen.c:36: 警告:函数声明不是一个原型
gcc -pthread -shared build/temp.linux-x86_64-2.7/mydlopen.o -L/usr/lib64 -L/usr/local/lib -ldl -lpython2.7 -o build/lib.linux-x86_64-2.7/mydlopen.so
running install_lib
copying build/lib.linux-x86_64-2.7/mydlopen.so -> /usr/local/lib/python2.7/site-packages
running install_egg_info
Removing /usr/local/lib/python2.7/site-packages/mydlopen-0.0.0-py2.7.egg-info
Writing /usr/local/lib/python2.7/site-packages/mydlopen-0.0.0-py2.7.egg-info


6)
$ python


Python 2.7.13 (default, Jun 27 2017, 13:39:52)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mydlopen
>>> mydlopen.getSum(1,3)
1+3=4


2. 利用ctypes库直接调用库文件

1)
$ python


Python 2.7.13 (default, Jun 27 2017, 13:39:52)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> dl = ctypes.cdll.LoadLibrary
>>> lib = dl("./libfunc.so")
>>> lib.sum(1,4)
1+4=5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python ctypes 扩展库