我知道你可以添加Writables成员:
struct PyMemberDef * PyTypeObject.tp_members
但我不想将自己局限于特定数量的属性。所以我根据Andrew Floren解决方案创建了一个带有 __ dict __ 的对象:Create a Python type from C that implements a __dict__?
我现在可以在Python中添加属性,但是如果我想在C中添加属性呢? 如何在C中使用 __ dict __ 向对象添加属性?
PyObject with __dict __...
typedef struct {
PyObject_HEAD
PyObject* dict;
} BarObject;
static PyTypeObject BarObject_Type = {
PyObject_HEAD_INIT(NULL)
};
PyMODINIT_FUNC
initFoo(void)
{
PyObject *m;
m = Py_InitModule("Foo", NULL);
if (m == NULL)
return;
BarObject_Type.tp_new = PyType_GenericNew;
BarObject_Type.tp_name = "Foo.Bar";
BarObject_Type.tp_basicsize = sizeof(BarObject);
BarObject_Type.tp_getattro = PyObject_GenericGetAttr;
BarObject_Type.tp_setattro = PyObject_GenericSetAttr;
BarObject_Type.tp_flags = Py_TPFLAGS_DEFAULT;
BarObject_Type.tp_dictoffset = offsetof(BarObject,dict);
BarObject_Type.tp_doc = "Doc string for class Bar in module Foo.";
if (PyType_Ready(&BarObject_Type) < 0)
return;
Py_INCREF(&BarObject_Type);
PyModule_AddObject(m, "Bar", (PyObject*)&BarObject_Type);
}
答案 0 :(得分:0)
解决方案: 基本上dict偏移量必须是dict类型的PyObject
BarObject *bar = PyObject_New(BarObject, &BarObject_Type);
bar->dict = PyDict_New();
PyObject_SetAttrString((PyObject*)bar, "none", Py_None);