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. Android明明可以直接分享,为什么还要用微信开放平台、微博开放平台的sdk?2. javascript - 单页面应用怎么监听ios微信返回键?3. angular.js - 在ionic下,利用javascript导入百度地图,pc端可以显示,移动端无法显示4. nginx - 关于javaweb项目瘦身问题,前期开发后,发现项目占用存贮空间太大,差不多1.2个G,怎么实现瘦身,动态页面主要是jsp。5. css3 - 求教个问题,关于响应式布局,跟ipad有关,媒体查询失效?6. javascript - 如何保证几个ajax提交成功;7. css - 浏览器缩放分辨率为什么布局会变8. angular.js - 百度支持_escaped_fragment_吗?9. vue.js - vue apache 代理设置10. 我在centos容器里安装docker,也就是在容器里安装容器,报错了?
