Pregunta

Estoy intentando escribir un envoltorio de Python para una función C. Después de escribir todo el código, y conseguir que para compilar, Python no puede importar el módulo. Estoy siguiendo el ejemplo dado aquí . Lo reproduzco aquí, después de la fijación de algunos errores tipográficos. Hay una myModule.c archivo:

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

Desde que estoy en un Mac con MacPorts pitón, compilo como

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

Sin embargo, me sale un error cuando intento importar a él.

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

¿Por qué no puedo importar que?

¿Fue útil?

Solución

Dado que está utilizando un compilador de C ++, nombres de función será destrozado (por ejemplo, mis mangles g++ void initmyModule() en _Z12initmyModulev). Por lo tanto, el intérprete de Python no encontrará función init del módulo.

Es necesario el uso ya sea un compilador C llana, o conexión de la fuerza a través de su módulo de C con un extern "C" directiva :

#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 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top