[C++-sig] Re: Creating an instance of a python class derived from a C++ object from C++
David Abrahams
dave at boost-consulting.com
Sun Jul 11 01:49:17 CEST 2004
"Brian Hall" <bhall at gamers-fix.com> writes:
>>
>> Now say I want to dynamically create an instance of a python class derived
>
>> from MyCppClass like so:
>>
>> class MyPythonClass(MyCppClass):
>> def SomeFunction(self):
>> return 42
>>
>> But I want to do this from C++, not Python... how would I do this?
>
> Use the metaclass interface:
>
> // returns a new class
> object make_bar
> {
> object bases = make_tuple(py_cState);
> dict attributes;
> attributes['x'] = 1;
> attributes['quack'] = quack;
>
> return py_cState.attr("__class__")("bar", bases, attributes);
> };
>
> ----------------
>
> While this is very very cool, I think you misunderstand me... I have the
> python script, and I want to instantiate a python object of type
> MyPythonClass from C++ not define it from C++.
Wrap this:
object make_one(object some_class)
{
return some_class();
}
in python:
>>> make_one(MyPythonClass)
>>> <my_module.MyPythonClass object at 0xwhatever>
--
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com
More information about the Cplusplus-sig
mailing list