Python C扩展:从引擎中提取参数 [英] Python C extension: Extract parameter from the engine
问题描述
我想使用Python对我的函数执行数学测试。可以访问Python的典型程序是:
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;
}
我的问题是:如何提取参数 a,b,c,d
到 PyObject
s?
My question is: How can I extract the parameters a,b,c,d
to PyObject
s?
推荐答案
PyRun_SimpleString()
在 __ main __
模块的上下文中执行代码。您可以使用 PyImport_AddModule()
检索此模块的引用,从此模块获取全局字典并查找变量:
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");
而不是使用这种方法,你最好创建一个新的 c>全局字符 c> c:> c>
字典并使用 PyRun_String
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);
这样,您不需要先将表达式的结果存储在某个变量中,然后从 __ main __
的全局范围中提取它。您仍然可以使用变量来存储中间结果,然后可以从上面的全局变量
中提取。
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.
这篇关于Python C扩展:从引擎中提取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!