【问题标题】:.so module doesnt import in python: dynamic module does not define init function.so 模块未在 python 中导入:动态模块未定义 init 函数
【发布时间】:2010-11-06 07:52:07
【问题描述】:

我正在尝试为 C 函数编写一个 python 包装器。编写完所有代码并编译后,Python 无法导入模块。我正在按照here 给出的示例进行操作。在修正了一些错别字后,我在这里复制它。有一个文件myModule.c:

#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);
}

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

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

为什么我不能导入?

【问题讨论】:

  • 你的代码好像有点乱码。
  • @Ignacio:我只是想按照示例进行操作。有没有更简单的例子可以指点我?
  • 顶部框中的代码是否真的反映了您在源文件中的内容?
  • @Ignacio。对不起,你是对的。当我从文件中复制它时它搞砸了。我重新复制了代码。它现在反映了我在源文件中的内容。

标签: c++ python c python-c-api python-extensions


【解决方案1】:

由于您使用的是 C++ 编译器,因此函数名称将是 mangled(例如,我的 g++void initmyModule() 转换为 _Z12initmyModulev)。因此,python 解释器不会找到您模块的 init 函数。

您需要使用纯 C 编译器,或者使用 extern "C" 指令强制整个模块的 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 

【讨论】:

  • 文档中给出的PyMODINIT_FUNC 宏将为您处理此问题。
  • @IgnacioVazquez-Abrams:您能否详细说明如何执行您的解决方案?谢谢。
猜你喜欢
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
相关资源
最近更新 更多