代码之家  ›  专栏  ›  技术社区  ›  highBandWidth

.so模块在python中不导入:动态模块不定义init函数

  •  7
  • highBandWidth  · 技术社区  · 14 年前

    here

    #include <Python.h>
    
    /*
     * Function to be called from Python
     */
    static PyObject* py_myFunction(PyObject* self, PyObject* args)
    {
        char *s = "Hello from C!";
        return Py_BuildValue("s", s);
    }
    /*
     * Bind Python function names to our C functions
     */
    static PyMethodDef myModule_methods[] = {
        {"myFunction", py_myFunction, METH_VARARGS},
        {NULL, NULL}
    };
    
    /*
     * Python calls this to let us initialize our module
     */
    void initmyModule()
    {
        (void) Py_InitModule("myModule", myModule_methods);
    }
    

    因为我使用Macports python在Mac上,所以我将其编译为

    $ g++ -dynamiclib -I/opt/local/Library/Frameworks/Python.framework/Headers -lpython2.6 -o myModule.dylib myModule.c
    $ mv myModule.dylib myModule.so
    

    但是,当我尝试导入它时出错。

    $ ipython
    In[1]: import myModule
    ---------------------------------------------------------------------------
    ImportError                               Traceback (most recent call last)
    
    /Users/.../blahblah/.../<ipython console> in <module>()
    
    ImportError: dynamic module does not define init function (initmyModule)
    

    为什么我不能进口?

    1 回复  |  直到 12 年前
        1
  •  5
  •   Frédéric Hamidi    14 年前

    由于您使用的是C++编译器,函数名称将是 mangled g++ void initmyModule() 进入之内 _Z12initmyModulev ). 因此,python解释器找不到模块的init函数。

    您需要使用普通的C编译器,或者在整个模块中使用 extern "C"

    #ifdef __cplusplus
    extern "C" {
    #endif 
    
    #include <Python.h>
    
    /*
     * Function to be called from Python
     */
    static PyObject* py_myFunction(PyObject* self, PyObject* args)
    {
        char *s = "Hello from C!";
        return Py_BuildValue("s", s);
    }
    
    /*
     * Bind Python function names to our C functions
     */
    static PyMethodDef myModule_methods[] = {
        {"myFunction", py_myFunction, METH_VARARGS},
        {NULL, NULL}
    };
    
    /*
     * Python calls this to let us initialize our module
     */
    void initmyModule()
    {
        (void) Py_InitModule("myModule", myModule_methods);
    }
    
    #ifdef __cplusplus
    }  // extern "C"
    #endif