Calling a python method from C/C++, and extracting

2019-01-05 09:20发布

I'd like to call a custom function that is defined in a python module from C. I have some preliminary code to do that, but it just prints the output to stdout.

mytest.py

import math

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

test.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;
}

How can I extract the return value into a C double and use it in C?

7条回答
Ridiculous、
2楼-- · 2019-01-05 10:20

To prevent the extra .py file as in the other answers, you can just retrieve the __main__ module, which is created by the first call to PyRun_SimpleString:

PyObject *moduleMainString = PyString_FromString("__main__");
PyObject *moduleMain = PyImport_Import(moduleMainString);

PyRun_SimpleString(
    "def mul(a, b):                                 \n"\
    "   return a * b                                \n"\
);

PyObject *func = PyObject_GetAttrString(moduleMain, "mul");
PyObject *args = PyTuple_Pack(2, PyFloat_FromDouble(3.0), PyFloat_FromDouble(4.0));

PyObject *result = PyObject_CallObject(func, args);

printf("mul(3,4): %.2f\n", PyFloat_AsDouble(result)); // 12
查看更多
登录 后发表回答