是否可以将 C 实例发送到 python 代码?只是为了解释我想要实现的目标:
我有这样的 C 代码:
主.C
#include <Python.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程序 示例.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函数的原因是更新一些数据,而我不想通过return来更新。
最佳答案
您需要一个 myCFunction 的包装器,它接受并解析 PyObject * 并返回 PyObject *。 https://docs.python.org/2/extending/embedding.html
类似于
PyObject* myCFunct(PyObject* args) {
// do something
return PyTrue;
}
关于python - 将 C 实例传递给 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25606919/