8

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

私はMacportspythonを搭載した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)

インポートできないのはなぜですか?

4

1 に答える 1

5

C++ コンパイラを使用しているため、関数名はマングルされます (たとえば、私のmangles into )。したがって、Python インタープリターはモジュールの init 関数を見つけられません。g++void initmyModule()_Z12initmyModulev

プレーンな 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 
于 2010-11-06T12:21:28.397 に答える