2014-09-29 44 views
1

我使用教程从python.org “Python嵌入在另一个应用程序”如何检索用C编写的调用函数的Python模块的名称?

如何检索Python模块的名称调用C语言编写的函数:

static int numargs=0; 

/* Return the number of arguments of the application command line */ 
static PyObject* 
emb_numargs(PyObject *self, PyObject *args) 
{ 
    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} 
}; 
+1

我不明白”我可以在这个函数中有模块名称吗?“手段。你可以解释吗? – Veedrac 2014-09-29 08:27:16

+0

不太清楚模块名称是什么意思。通常C中的模块都是文件,而且你会引用一个文件名。然而,这是不可能的,因为你的函数是静态的,不能在它的文件之外被引用。 – Steen 2014-09-29 08:55:05

回答

0

我已经embeddded蟒蛇到我的C++应用程序。但需要动态添加模块。 与

Py_InitModule("module1", EmbMethods); 
Py_InitModule("module2", EmbMethods); 

相同的回调

static PyMethodDef EmbMethods[] = { 
    {"some_func", some_func, METH_VARARGS,""}, 
    {NULL, NULL, 0, NULL} 
}; 

需要像这样

static PyObject* some_func(PyObject *self, PyObject *args) 
{ 
    char *p; 
    if(!PyArg_ParseTuple(args, "s",&p)) 
     return NULL; 

    std::cout<<self->module_name //<<<<<<<< self always == NULL , why? 

    return Py_BuildValue("i", numargs); 
} 

python脚本

import module1 
print module1.some_func() 
print module2.some_func() 

输出预计: “莫dule1“ ”module2“

+0

建议其他解决方案,如果你有一个 – 2014-09-29 10:18:47

相关问题