2014-09-01 52 views
-2

是否可以將C實例發送給Python代碼?只是爲了解釋我想實現:將C實例傳遞給Python

我有一個C代碼:

MAIN.C

 

    #include &ltPython.h> 

    int myCFunction(int someVariable) 
    { 
     // do some operation 
    } 

    int main() 
    { 
     Py_Initialize(); 
     PyObject *pName ... 
     ... 
     pName = PyString_FromString("example"); //Call example.py 
     ... 
     pFunc = PyDict_GetItemString(pDict, "add"); // Call the method in example.py 
     pArgs = PyTuple_New(3); 
     pValue = PyInt_FromLong(3); 
     PyTuple_SetItem(pArgs, 0, pValue); 
     PyTuple_SetItem(pArgs, 1, pValue); 
     // I want to pass this instance as well, may be as a parameter 
     // PyTuple_SetItem(pArgs, 1, /*instance?? */); 
     return 0; 
    } 


我的Python程序 example.py

 

    # Returns the sum of two numbers. 
    def add(a, b, instance): 
     # using the instance, I want to trigger C function 'myCFunction' 
     return a+b 


C你讓我知道我怎麼能做到這一點?我回撥C函數的原因是更新一些數據,我不想通過返回來完成。

+1

什麼意思 「的C實例」 或 「這種情況下」?什麼樣的實例? – michaelmeyer 2014-09-01 13:34:09

+0

編程中的'this'表示調用程序實例。我想從main.c調用example.py,在example.py中調用myCFunction(從調用實例{this})來更新一些值。 – programmer 2014-09-01 14:16:41

+0

所以你實際上提出了兩個問題:1)如何從C調用Python函數? 2)我如何從Python調用C函數?這兩個都在Python C API文檔中得到了解答。 – michaelmeyer 2014-09-01 14:28:39

回答

2

你需要一個myCFunction包裝器來接受並分析PyObject *並返回一個PyObject *。 https://docs.python.org/2/extending/embedding.html

喜歡的東西

PyObject* myCFunct(PyObject* args) { 
    // do something 
    return PyTrue; 
} 
+0

謝謝。但是,在上面的例子中,你如何從example.py中調用它? – programmer 2014-09-01 14:12:49