将C实例传递给Python

2024-10-02 12:30:37 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以将C实例发送到python代码?只是为了解释我想要达到的目标:

我有这样的C代码:

主C


    #include &ltPython.h&gt

    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来实现。你知道吗


Tags: theinstance代码pyaddreturnexamplecall
1条回答
网友
1楼 · 发布于 2024-10-02 12:30:37

在myCFunction周围需要一个包装器,它接受并解析PyObject*并返回一个PyObject*。https://docs.python.org/2/extending/embedding.html

像这样的

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

相关问题 更多 >

    热门问题