从python 2迁移到python 3-嵌入问题
我正在将一个嵌入python的应用程序从2.7版迁移到3.3版。应用程序通过使用适当的数据调用从python 2迁移到python 3-嵌入问题,python,python-2.7,python-3.x,porting,python-c-api,Python,Python 2.7,Python 3.x,Porting,Python C Api,我正在将一个嵌入python的应用程序从2.7版迁移到3.3版。应用程序通过使用适当的数据调用Py\u InitModule()使函数可用于脚本。只是为了让像我这样的穷家伙感到恼火,api在Python3中被删除,取而代之的是采用相当复杂结构的PyModule\u Create 当我使用python2 api时,一切正常,当我使用新的v3 api时,api加载正常(返回有效指针),但在脚本中使用公开函数将产生错误: //导入错误:没有名为“emb”的模块 其中emb是我的模块名。非常讨厌!我已经
Py\u InitModule()
使函数可用于脚本。只是为了让像我这样的穷家伙感到恼火,api在Python3中被删除,取而代之的是采用相当复杂结构的PyModule\u Create
当我使用python2 api时,一切正常,当我使用新的v3 api时,api加载正常(返回有效指针),但在脚本中使用公开函数将产生错误:
//导入错误:没有名为“emb”的模块
其中emb是我的模块名。非常讨厌!我已经包括了两个版本,也许有人可以帮助。
我在这里遵循了移植指南:
这和我做的完全一样。我无法理解为什么api被更改
static int numargs=0;
static PyObject*
emb_numargs(PyObject *self, PyObject *args) //what this function does is not important
{
if(!PyArg_ParseTuple(args, ":numargs"))
return NULL;
return Py_BuildValue("i", numargs);
}
static PyMethodDef EmbMethods[] = {
{"numargs", emb_numargs, METH_VARARGS,
"Return the number of arguments received by the process."},
{NULL, NULL, 0, NULL}
};
#ifdef PYTHON2
//works perfect with Pytho 27
Py_InitModule("emb", EmbMethods);
PyRun_SimpleString(
"import emb\n"
"print(emb.numargs())\n"
);
#else
static struct PyModuleDef mm2 = {
PyModuleDef_HEAD_INIT,
"emb",
NULL,
sizeof(struct module_state),
EmbMethods,
NULL,
0,
0,
NULL
};
//does not work with python 33:
//ImportError: No module named 'emb'
PyObject* module = PyModule_Create(&mm2);
PyRun_SimpleString(
"import emb\n"
"print(emb.numargs())\n"
);
#endif
基于这一点,他们似乎已经改变了导入模块的方式
以下是希望对您有用的内容:
// this replaces what is currently under your comments
static PyObject*
PyInit_emb(void)
{
return PyModule_Create(&mm2);
}
numargs = argc;
PyImport_AppendInittab("emb", &PyInit_emb);
太好了,谢谢!虽然我真的开始不喜欢python c api了。。。对于其他人:请注意,应在
pyinitilize()
之前调用PyImport\u AppendInittab
,否则将找不到导入。