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. linux - 【已解决】fabric部署的Python项目Apache启动之后提示403Forbidden该如何解决?3. 上传多图时,最后一张图为缩略图,想设置第一张图为缩略图怎么解决?4. python - 如何获取rabbitmq连接的celery的个数5. 怎样用python给mp3添加封面?6. js怎样实现在类似qq的联系人分组中进行搜索后,又可恢复原分组的界面?7. 数据库 - Mysql的存储过程真的是个坑!求助下面的存储过程哪里错啦,实在是找不到哪里的问题了。8. javascript - 百度地图一开始设置了中心点,怎么通过按钮在调转到对应的中心点????9. mysql优化 - mysql 一张表如果不能确保字段列长度一致,是不是就不需要用到char。10. python - 如何将文本文件的CR换行符换成LF换行符?