Define a global in a Python module from a C API

倖福魔咒の 提交于 2019-11-27 06:29:46

问题


I am developing a module for Python using a C API. How can I create a variable that is seen as global from Python?

For example, if my module is module, I want to create a variable g that does this job:

import module
print module.g

In particular, g is an integer.

Solution from Alex Martelli

PyObject *m = Py_InitModule("mymodule", mymoduleMethods);
PyObject *v = PyLong_FromLong((long) 23);

PyObject_SetAttrString(m, "g", v);
Py_DECREF(v);

回答1:


You can use PyObject_SetAttrString in your module's initialization routine, with first argument o being (the cast to (PyObject*) of) your module, second argument attr_name being "g", third argument v being a variable

PyObject *v = PyLong_FromLong((long) 23);

(or whatever other value of course, 23 is just an example!-).

Do remember to decref v afterwards.

There are other ways, but this one is simple and general.



来源:https://stackoverflow.com/questions/3001239/define-a-global-in-a-python-module-from-a-c-api

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