CPython - 向包含 __dict__ 的新类型添加属性

CPython - Adding an attribute to a new type that contains a __dict__

我知道您可以添加 Writables 成员:

struct PyMemberDef * PyTypeObject.tp_members

但我不想将自己限制在特定数量的属性上。所以我根据 Andrew Floren 解决方案用 __dict__ 创建了一个对象:Create a Python type from C that implements a __dict__?

我现在可以在 Python 中添加属性,但是如果我想在 C 中添加属性怎么办? 如何在 C 中使用 __dict__ 向对象添加属性?

PyObject 与 __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);
}

解决方法: 基本上 dict 偏移量必须是 dict

类型的 PyObject
BarObject *bar = PyObject_New(BarObject, &BarObject_Type);
bar->dict = PyDict_New();
PyObject_SetAttrString((PyObject*)bar, "none", Py_None);