首頁  >  問答  >  主體

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 */
};

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])

錯誤訊息

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
怪我咯怪我咯2711 天前571

全部回覆(1)我來回復

  • ringa_lee

    ringa_lee2017-05-18 11:02:29

    哎,早上醒來突然想到,趕緊試了一下。

    出現這個問題是因為在編譯的時候需要加 -lwiringPi 选项来引用这个库,但是我仔细看了以下执行 python setup.py build 之后执行的编译命令,根本就没有加这个选项,解决方式很简单,只需要修改一下setup.py,在Extension里面加上 libraries = ['wiringPi'] 這個參數就行了,修改後的setup.py變成如下樣子

    from distutils.core import setup, Extension
    
    dht11module = 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])

    回覆
    0
  • 取消回覆