我正在努力学习如何正确使用Python / C API – 我真正需要做的就是读取一个全局变量(在我的案例中是字典 – 但我从一个简单的整数变量开始).
使用讨论:
How to access a Python global variable from C?
那里答案的来源:
http://bytes.com/topic/python/answers/705918-c-api-embedded-python-how-get-set-named-variables
我写了这个小东西:
Python代码(tryStuff.py):
var1 = 1
var2 = ['bla', 'blalba']
var3 = {"3" : "Three", "2" : "Two", "1" : "One", "0" : "Ignition!"}
print "end of file - tryStuff!!"
C代码(embedPythonTry.c):
#include
int main(int argc, char **argv){
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('')");
PyImport_ImportModule("tryStuff");
printf("After the import, before the addition
");
PyObject *mainModule = PyImport_AddModule("__main__");
PyObject *var1Py = PyObject_GetAttrString(mainModule, "var1");
int var1Int = PyInt_AsLong(var1Py);
printf("var1=%d ; var1==NULL: %d
", var1Int, var1Py==NULL);
Py_XDECREF(var1Py);
Py_Finalize();
return 0;
}
运行此c程序的输出是:
end of file - tryStuff!!
After the import, before the addition
var1=-1 ; var1==NULL: 1
这意味着Python解释器找到并运行正确的Python脚本,但不知何故它无法管理读取变量(var1).
任何人都可以发现问题 – 我有点迷失了.它看起来像应用Python / C API的最简单的情况,但它不起作用.
我错过了什么?