python - 将 C 实例传递给 Python

标签 python c

是否可以将 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/

相关文章:

python - 如何修改解析器计算器语法以继续对先前结果进行计算?

python - 将 pandas python 中的 bool 输出切换为字符串

python - 将 re 与 rsplit 一起使用

c - 如何在 C/C++ 中写入不同线程的堆栈?

c++ - 是否有开源音频流客户端或框架?

Python测试字符串是否有 "%"并且不让它中断

python - pandas - 将列标签分配给记录值作为最小/最大函数的结果

c++ - 可以优化 b&&0

c - Mallocing 二维数组,尝试打印字符串后崩溃

c - 家庭作业问题,国际象棋皇后的可用字段