如何从C访问一个Python全局变量? [英] How to access a Python global variable from C?
问题描述
我有一个Python脚本一些全局变量。在脚本调用成C的一些功能 - 它可以设置这些变量之一,而在C和如果是,如何
?我AP preciate,这不是一个很不错的设计摆在首位,但我需要做一个小的变化对现有code,我不想走上现有的大规模的重构脚本。
我不是一个Python大师,但我发现这个问题有意思,所以我用Google搜索左右。 这是在蟒蛇嵌入API的第一主打 - 帮助?
如果属性属于全局
一个模块的范围,那么你可以使用
PyImport_AddModule来获得一个句柄
到模块的对象。例如,如果
你想获得的价值
整数主要命名模块
取得foobar,你会做以下内容:的PyObject * M = PyImport_AddModule(__ main__);
*的PyObject V = PyObject_GetAttrString(男,FOOBAR);INT foobar的= PyInt_AsLong(V);Py_DECREF(五);
块引用>I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?
I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.
解决方案I'm not a python guru, but I found this question interesting so I googled around. This was the first hit on "python embedding API" - does it help?
If the attributes belong to the global scope of a module, then you can use "PyImport_AddModule" to get a handle to the module object. For example, if you wanted to get the value of an integer in the main module named "foobar", you would do the following:
PyObject *m = PyImport_AddModule("__main__"); PyObject *v = PyObject_GetAttrString(m,"foobar"); int foobar = PyInt_AsLong(v); Py_DECREF(v);
这篇关于如何从C访问一个Python全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!