Python C-API Making len(…) work with extension class?

As Igniacio says, the correct way is to fill the tp_as_sequence member of your typeobject. Here is a minimal example.

As Igniacio says, the correct way is to fill the tp_as_sequence member of your typeobject. Here is a minimal example: #include /** * C structure and methods definitions */ typedef struct { PyObject_HEAD; } TestObject; static Py_ssize_t TestClass_len(TestObject* self) { return 55; } /** * Python definitions */ static PySequenceMethods TestClass_sequence_methods = { TestClass_len, /* sq_length */ }; static PyTypeObject TestClass = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "testmodule. TestClass", /*tp_name*/ sizeof(TestObject), /*tp_basicsize*/ }; /** * Module entry point */ #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC inittestmodule(void) { PyObject* m; TestClass.

Tp_new = PyType_GenericNew; TestClass. Tp_as_sequence = &TestClass_sequence_methods; TestClass. Tp_flags = Py_TPFLAGS_DEFAULT; if (PyType_Ready(&TestClass) This would look more like the code you pasted, except that you defined __len__ in the C methods table, which doesn't work.

TypeError: object of type 'test_module. Test_class' has no len()" with "{"len",(PyCFunction)&TestClass_GetLen,METH_O,""}" :( – Fire Lancer Jan 14 '10 at 14:50 Could you paste the complete C code? – Luper Rouch Jan 14 '10 at 16:01 Ok I added all the code for TestClass – Fire Lancer Jan 16 '10 at 11:06 Your mistake was to define __len__ in the C methods table, edited answer with a working example.

– Luper Rouch Jan 18 '10 at 2:36.

The tp_as_sequence member of the typeobject structure should be filled in with something that has its sq_length member populated.

Indeed, and it's documented in docs.python. Org/c-api/typeobj. Html#tp_as_sequence .

– Antoine P. Jan 16 '10 at 11:24.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions