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. java - Ckeditor上传图片时出现mutipartRequest 转换异常2. python - Django ManyToManyField 字段数据在 admin后台 显示不正确,这是怎么回事?3. javascript - 怎样去除数组里的几个值,只提供该数组的下标的话4. php由5.3升级到5.6后,登录网站,返回的是php代码,不是登录界面,各位大神有知道的吗?5. 老师无限级分类有点难哟 不好理解6. javascript - swiper.js嵌套了swiper 初始设置不能向下一个滑动 结束后重新初始7. mysql 能不能创建一个 有列级函数 的联合视图?8. javascript - vue-cli热更新的问题【webpack配置】9. node.js - webpack required打包问题10. android - jni生成的char*在NewStringUTF时报错

网公网安备