I once read that it is possible to use a python base class for a C
extension class. To be precise, I want to achieve the following
behavior:
class PythonClass :
pass
class CClass(PythonClass) :
"this class should be implemented as C extension"
pass
Unfortunately, google could not find me the right reference. Does
anyone know how to do it, or where I can find relevant information?
Thanks,
- harold -
--
Je me suis enfermé dans mon amour -- je rève.
-- Paul Eluard
> "harold fellermann" <harold.f...@upf.edu> wrote in message
> news:mailman.378.11186789...@python.org...
> Hi all,
>
> I once read that it is possible to use a python base class for a C
> extension class.
On 14.06.2005, at 09:29, Grigoris Tsolakidis wrote:
> There was good article of how to do this on DDJ home page www.ddj.com
unfortunately, I could not find it yet. I managed to do the following:
I the initmodule function of my extension, I import the module and look
for the class I want to use as a base class:
PyObject *base_module = PyImport_ImportModule("module_name");
if (!base_module) return;
PyObject *base_class = PyMapping_GetItemString(
PyModule_GetDict(base_module,"BaseClass")
);
if (!base_class) return;
This gives me a pointer to the class I want to use as base class.
Does anyone know how to assign this to the extension class? I tried
to build a tuple (BaseClass,) and assign it (after the respective
PyType_Ready call) to CClass.__bases__ like this:
PyObject_SetAttrString(
&cclassType,
"__bases__",
Py_BuildValue("(O,)",base_class)
);
but this raises a TypeError when executed during import:
TypeError: can't set attributes of built-in/extension type
'ext_module.CClass'
Any ideas how to proceed?
- harold -
--
You can imagine the opposite
-- Maurizio Nannucci
--Scott David Daniels
Scott....@Acm.Org
/* import the module that holds the base class */
PyObject *base_module = PyImport_ImportModule("module_name");
if (!base_module) return;
/* get a pointer to the base class */
PyObject *base_class = PyMapping_GetItemString(
PyModule_GetDict(base_module,"BaseClass")
);
if (!base_class) return;
/* assign it as base class */
cclassType.tp_bases = Py_BuildValue("(O)",BaseClass);
I am doing all this before the call to PyType_Ready() -- as
Scoot Daniels suggested. Using the python API's SetAttrString()
did not work (I suppose for the same reason, why assigning
cls.__bases__ does not work in pure python either).
I also checked
cclassType.tp_base = (PyTypeObject *) base_class;
which also works and I am not aware of the difference of these two
slots.
Anyway, for my simple purposes it works just fine.
- harold -
--
"Mr Ghandi, what do you think of western civilization?"
"Oh, this would be a great idea."