C语言编写的Python模块加载时提示.so中的函数未找到?
问题描述
我尝试通过C语言编写一个Python的模块,但是我的C程序本身又依赖于一个第三方的库(libwiringPi.so),当我在Python源程序中import我生成的库时,会提示函数未定义,这些函数都是那个第三方库里的,我应该怎样编译才能让我编译出的模块可以动态链接那个库?
我也尝试过使用gcc手动编译动态链接库,然后用ctyes,但是报一样的错误;生成模块的C代码和setup.py代码都是基于Python源码包中的demo程序。
我的C程序代码
/* Example of embedding Python in another program */#include 'python2.7/Python.h'#include <wiringPi.h>void initdht11(void); /* Forward */int main(int argc, char **argv){ /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initdht11(); /* Exit, cleaning up the interpreter */ Py_Exit(0); return 0;}/* A static module *//* ’self’ is not used */static PyObject *dht11_foo(PyObject *self, PyObject* args){ wiringPiSetup(); return PyInt_FromLong(42L);}static PyMethodDef dht11_methods[] = { {'foo', dht11_foo, METH_NOARGS, 'Return the meaning of everything.'}, {NULL, NULL} /* sentinel */};voidinitdht11(void){ PyImport_AddModule('dht11'); Py_InitModule('dht11', dht11_methods);}
setup.py
from distutils.core import setup, Extensiondht11module = Extension(’dht11’, library_dirs = [’/usr/lib’], include_dirs = [’/usr/include’], sources = [’math.c’])setup (name = ’dht11’, version = ’1.0’, description = ’This is a demo package’, author = ’Martin v. Loewis’, author_email = ’martin@v.loewis.de’, url = ’https://docs.python.org/extending/building’, long_description = ’’’This is really just a demo package.’’’, ext_modules = [dht11module])
错误信息
Traceback (most recent call last): File 'test.py', line 1, in <module> import dht11ImportError: /usr/local/lib/python2.7/dist-packages/dht11.so: undefined symbol: wiringPiSetup
问题解答
回答1:哎,早上醒来突然想到,赶紧试了一下。
出现这个问题是因为在编译的时候需要加 -lwiringPi 选项来引用这个库,但是我仔细看了以下执行 python setup.py build 之后执行的编译命令,根本就没有加这个选项,解决方式很简单,只需要修改一下setup.py,在Extension里面加上 libraries = [’wiringPi’] 这个参数就行了,修改后的setup.py变成如下样子
from distutils.core import setup, Extensiondht11module = Extension(’dht11’, library_dirs = [’/usr/lib’], #指定库的目录 include_dirs = [’/usr/include’], #制定头文件的目录 libraries = [’wiringPi’], #指定库的名称 sources = [’math.c’])setup (name = ’dht11’, version = ’1.0’, description = ’This is a demo package’, author = ’Martin v. Loewis’, author_email = ’martin@v.loewis.de’, url = ’https://docs.python.org/extending/building’, long_description = ’’’This is really just a demo package.’’’, ext_modules = [dht11module])
相关文章:
1. python - 有一个函数名(字符串形式),如何能够调用这个函数?2. update方法不能更新字段值为0的数据3. 请教一条mysql的sql语句写法;4. 这段代码既不提示错误也看不到结果,请老师明示错在哪里,谢谢!5. layer.alert(’请输入用户名’,{icon:2})无法弹出窗口,是哪个包没引进来?6. mysql这个int型的4字节是什么意思??7. phpstuty 修改完监听端口,apache无法启动8. mysql - myisAm为什不支持行锁?9. mysql函数unix_timestamp如何处理1970.1.1以前的数据?10. phpstady在win10上运行

网公网安备