.soモジュールはpythonでインポートしません:動的モジュールはinit機能を定義しません
-
29-09-2019 - |
質問
私はC関数のためにPythonラッパーを書き込もうとしています。すべてのコードを書き込み、コンパイルした後、Pythonはモジュールをインポートできません。私は与えられた例に従っています ここ. 。いくつかのタイプミスを修正した後、ここでそれを再現します。ファイル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);
}
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)
なぜインポートできないのですか?
解決
C ++コンパイラを使用しているため、機能名は 壊れた (たとえば、私の g++
マングル void initmyModule()
の中へ _Z12initmyModulev
)。したがって、Pythonインタープリターはモジュールのinit機能を見つけられません。
プレーンCコンパイラを使用するか、モジュール全体で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
所属していません StackOverflow