您的位置:首页技术文章
文章详情页

C语言编写的Python模块加载时提示.so中的函数未找到?

【字号: 日期:2022-07-02 08:45:16浏览:49作者:猪猪

问题描述

我尝试通过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])

标签: Python 编程
相关文章: