Defining global in Python module from C API

I am developing a module for Python using the C API. How to create a variable that is considered global from Python?

For example, if my module module, I want to create a variable gthat performs this task:

import module
print module.g

In particular, gis 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);
+3
source share
1 answer

PyObject_SetAttrString , o (cast to (PyObject*) of ) , attr_name - "g", v -

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

( , , 23 ! -).

v.

, .

+3

Source: https://habr.com/ru/post/1749102/


All Articles