简体   繁体   English

如何从C访问Python全局变量?

[英]How to access a Python global variable from C?

I have some global variables in a Python script. 我在Python脚本中有一些全局变量。 Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how? 该脚本中的一些函数调用C - 是否可以在C中设置其中一个变量,如果是,如何?

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. 我不是一个蟒蛇大师,但我发现这个问题很有趣所以我google了一下。 This was the first hit on "python embedding API" - does it help? 是“python嵌入API”的第一个热门 - 它有帮助吗?

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. 如果属性属于模块的全局范围,则可以使用“PyImport_AddModule”来获取模块对象的句柄。 For example, if you wanted to get the value of an integer in the main module named "foobar", you would do the following: 例如,如果要在名为“foobar”的模块中获取整数的值,则执行以下操作:

 PyObject *m = PyImport_AddModule("__main__"); PyObject *v = PyObject_GetAttrString(m,"foobar"); int foobar = PyInt_AsLong(v); Py_DECREF(v); 

For anyone coming here from Google, here's the direct method: 对于来自谷歌的任何人来说,这是直接的方法:

PyObject* PyEval_GetGlobals()

https://docs.python.org/2/c-api/reflection.html https://docs.python.org/2/c-api/reflection.html

https://docs.python.org/3/c-api/reflection.html https://docs.python.org/3/c-api/reflection.html

The return value is accessed as a dictionary. 返回值作为字典访问。

I recommend using pyrex to make an extension module you can store the values in in python, and cdef a bunch of functions which can be called from C to return the values there. 我建议使用pyrex创建一个扩展模块,你可以将值存储在python中,并cdef一堆函数,可以从C调用它们返回值。

Otherwise, much depends on the type of values you're trying to transmit. 否则,很大程度上取决于您尝试传输的值的类型。

Are you willing to modify the API a little bit ? 您是否愿意稍微修改API?

  • You can make the C function return the new value for the global, and then call it like this: 您可以使C函数返回全局的新值,然后像这样调用它:

    my_global = my_c_func(...)

  • If you're using Robin or the Python C API directly, you can pass the globals dictionary as an additional parameter and modify it 如果您直接使用Robin或Python C API,则可以将全局字典作为附加参数传递并进行修改

  • If your global is always in the same module, Sherm's solution looks great 如果您的全局总是在同一个模块中,那么Sherm的解决方案看起来很棒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM