如何解析 python c 扩展中的对象?
How can I parse an object in a python c-extention?
我在 Python 中有一个对象,例如:
import test
class Test:
def __init__(self, n):
self.n = n
t = Test(4)
test.c_function(t)
我想在
中用 c 语言阅读它
static PyObject* py_c_function(PyObject* self, PyObject* args) {
PyObject obj;
if (!PyArg_ParseTuple(args, "O", &obj))
return NULL;
int n;
// I want to access the the n member of the object or create a new Test struct
return Py_BuildValue("i", n);
// or
return Py_BuildValue("i", test.n);
}
如何访问自定义 python 数据结构的 pyObject 中的成员?
我如何做相反的事情,将值赋给稍后将在内部调用的对象 python?
编辑:
根据 kpie 的建议,根据文档使用函数 PyObject_GetAttrString 这应该等同于 obj.n。
PyObject * o = PyObject_GetAttrString(&obj, "n");
long n;
n = PyLong_AsLong(o);
但是当我 运行 这个时,我得到了错误:
SystemError: ../Objects/dictobject.c:1438: bad argument to internal function
编辑 2
我正在使用 GCC 编译 c 代码:
gcc -I/usr/include/python3.8/ -shared -o test.so -fPIC test.c
然后在 python 脚本中添加
import test
函数 PyObject_GetAttrString(obj,"attr")
可以读取 python class 的属性,类似于 kpie 评论的 obj.attr。
问题是 PyObject obj;
这不是指针。
我在 Python 中有一个对象,例如:
import test
class Test:
def __init__(self, n):
self.n = n
t = Test(4)
test.c_function(t)
我想在
中用 c 语言阅读它static PyObject* py_c_function(PyObject* self, PyObject* args) {
PyObject obj;
if (!PyArg_ParseTuple(args, "O", &obj))
return NULL;
int n;
// I want to access the the n member of the object or create a new Test struct
return Py_BuildValue("i", n);
// or
return Py_BuildValue("i", test.n);
}
如何访问自定义 python 数据结构的 pyObject 中的成员?
我如何做相反的事情,将值赋给稍后将在内部调用的对象 python?
编辑:
根据 kpie 的建议,根据文档使用函数 PyObject_GetAttrString 这应该等同于 obj.n。
PyObject * o = PyObject_GetAttrString(&obj, "n");
long n;
n = PyLong_AsLong(o);
但是当我 运行 这个时,我得到了错误:
SystemError: ../Objects/dictobject.c:1438: bad argument to internal function
编辑 2
我正在使用 GCC 编译 c 代码:
gcc -I/usr/include/python3.8/ -shared -o test.so -fPIC test.c
然后在 python 脚本中添加
import test
函数 PyObject_GetAttrString(obj,"attr")
可以读取 python class 的属性,类似于 kpie 评论的 obj.attr。
问题是 PyObject obj;
这不是指针。