从C API定义Python模块中的全局 [英] Define a global in a Python module from a C API

查看:100
本文介绍了从C API定义Python模块中的全局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C API为Python开发一个模块。我如何创建一个从Python看来是全局的变量?

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

例如,如果我的模块是 module ,我想创建一个变量 g

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

import module
print module.g

特别是, g 是一个整数。

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

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


推荐答案

您可以使用 PyObject_SetAttrString ,在第一个参数 o 转换为(PyObject *) of)模块,第二个参数 attr_name 为g,第三个参数 v 是一个变量

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);

(或者其他任何值, 23 只是一个例子!)。

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

事后记得 v

还有其他方法,但这个很简单,一般。

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

这篇关于从C API定义Python模块中的全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆