python-embedding

Calling a python method from C/C++, and extracting its return value

随声附和 提交于 2019-11-26 15:04:32
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? As explained before, using PyRun_SimpleString seems to be a bad idea. You should

Create an object using Python&#39;s C API

独自空忆成欢 提交于 2019-11-26 13:01:35
问题 Say I have my object layout defined as: typedef struct { PyObject_HEAD // Other stuff... } pyfoo; ...and my type definition: static PyTypeObject pyfoo_T = { PyObject_HEAD_INIT(NULL) // ... pyfoo_new, }; How do I create a new instance of pyfoo somewhere within my C extension? 回答1: Call PyObject_New(), followed by PyObject_Init(). EDIT: The best way is to call the class object, just like in Python itself: /* Pass two arguments, a string and an int. */ PyObject *argList = Py_BuildValue("si",

Calling a python method from C/C++, and extracting its return value

时光怂恿深爱的人放手 提交于 2019-11-26 03:49:37
问题 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