从 C/C 调用 python 方法,并提取其返回值

新手上路,请多包涵

我想从 C 调用一个在 Python 模块中定义的自定义函数。我有一些初步代码可以做到这一点,但它只是将输出打印到标准输出。

我的测试.py

 import math

def myabs(x):
    return math.fabs(x)

测试.cpp

 #include <Python.h>

int main() {
    Py_Initialize();
    PyRun_SimpleString("import sys; sys.path.append('.')");
    PyRun_SimpleString("import mytest;");
    PyRun_SimpleString("print mytest.myabs(2.0)");
    Py_Finalize();

    return 0;
}

如何将返回值提取到 C double 并在 C 中使用它?

原文由 D R 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 810
2 个回答

如前所述,使用 PyRun_SimpleString 似乎不是一个好主意。

您绝对应该使用 C-API ( http://docs.python.org/c-api/ ) 提供的方法。

阅读介绍是了解其工作方式的第一件事。

首先,您必须了解作为 C API 的基本对象的 PyObject。它可以表示任何类型的 Python 基本类型(字符串、浮点数、整数、…)。

存在许多函数可以将例如 python 字符串转换为 char* 或 PyFloat 转换为 double。

首先,导入您的模块:

 PyObject* myModuleString = PyString_FromString((char*)"mytest");
PyObject* myModule = PyImport_Import(myModuleString);

然后获取对您的函数的引用:

 PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"myabs");
PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(2.0));

然后得到你的结果:

 PyObject* myResult = PyObject_CallObject(myFunction, args)

并回到 double :

 double result = PyFloat_AsDouble(myResult);

您显然应该检查错误(参见 Mark Tolonen 给出的链接)。

如果您有任何问题,请不要犹豫。祝你好运。

原文由 ThR37 发布,翻译遵循 CC BY-SA 2.5 许可协议

正如其他人已经提到的,这在 Python 文档 中得到了回答。但是,由于我来自 Python 并且没有太多使用 C/C++ 的经验,所以我在使用 Python 3 运行它时遇到了一些问题。所以这是我在其他帖子上花了一些时间后让 Python 文档运行的完整工作示例堆栈溢出:

文件 c_function.c

 #define PY_SSIZE_T_CLEAN
#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();

    // I had to add the following two lines to make it work
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");

    pName = PyUnicode_DecodeFSDefault(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyLong_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    if (Py_FinalizeEx() < 0) {
        return 120;
    }
    return 0;
}

文件 multiply.py

 def multiply(a,b):
    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c

我们需要编译和链接它。这可以通过以下命令完成:

 gcc c_function.c -c $(python3.6-config --cflags) -fPIC

其次是

gcc c_function.o $(python3.6-config --ldflags) -o call

以 Python 3.6 为例。之后,Python 文档中的示例可以由

./call multiply multiply 3 2

原文由 Tobbe 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题