I try to write a Python module in C language, but my C program itself depends on a third-party library (libwiringPi.so). When I import the library I generated in the Python source program, I will be prompted. The function is undefined. These functions are all in that third-party library. How should I compile so that the module I compile can dynamically link to that library?
I also tried to use gcc to manually compile the dynamic link library, and then used ctyes, but the same error was reported; the C code and setup.py code of the generated module are both based on the demo program in the Python source package.
My C program code
/* 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 */
};
void
initdht11(void)
{
PyImport_AddModule("dht11");
Py_InitModule("dht11", dht11_methods);
}
setup.py
from distutils.core import setup, Extension
dht11module = 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])
error message
Traceback (most recent call last):
File "test.py", line 1, in <module>
import dht11
ImportError: /usr/local/lib/python2.7/dist-packages/dht11.so: undefined symbol: wiringPiSetup
Hey, I woke up in the morning and suddenly thought of it, so I quickly tried it.
This problem occurs because you need to add
-lwiringPi
选项来引用这个库,但是我仔细看了以下执行python setup.py build
之后执行的编译命令,根本就没有加这个选项,解决方式很简单,只需要修改一下setup.py,在Extension里面加上libraries = ['wiringPi']
this parameter when compiling. The modified setup.py becomes as follows