2014-09-29 47 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

相關問題