Python C extension: Extract parameter from the engine

空扰寡人 提交于 2019-12-25 08:01:26

问题


I would like to use Python to perform Mathematics tests on my functions. A typical program that can gain access to Python is this:

#include <iostream>
#include <string>
#include <Python.h>
int RunTests()
{
    Py_Initialize();

    PyRun_SimpleString("a=5");
    PyRun_SimpleString("b='Hello'");
    PyRun_SimpleString("c=1+2j");
    PyRun_SimpleString("d=[1,3,5,7,9]");

    //question here

    Py_Finalize();
    return 0;
}

My question is: How can I extract the parameters a,b,c,d to PyObjects?


回答1:


PyRun_SimpleString() executes the code in the context of the __main__ module. You can retrieve a reference to this module using PyImport_AddModule(), get the globals dictionary from this module and lookup variables:

PyObject *main = PyImport_AddModule("__main__");
PyObject *globals = PyModule_GetDict(main);
PyObject *a = PyDict_GetItemString(globals, "a");

Instead of using this approach, you might be better off creating a new globals dictionary and using PyRun_String() to execute code in the context of that globals dict:

PyObject *globals = PyDict_New();
PyObject *a = PyRun_String("5", Py_single_input, globals, globals);

This way, you don't need to first store the result of your expression in some variable and then extract it from the global scope of __main__. You can still use variables to store intermediate results, which can then be extracted from globals as above.



来源:https://stackoverflow.com/questions/40041498/python-c-extension-extract-parameter-from-the-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!