[C++-sig] Instantiating a Python class from C++?
Pierre Barbier de Reuille
pierre.barbier at cirad.fr
Sat Aug 28 15:03:21 CEST 2004
I will suppose you have access to the module namespace containing the
derived class. I'll call this "module_namespace". So, you can retrieve
the class using Boost.Python very simply :
boost::python::object cls = module_namespace["DerivedClass"]
And now, you can create the object with :
boost::python::object obj = cls();
And to get a pointer to the underlying C++ object :
MyClass* cpp_obj = extract<MyClass*>(obj);
It should work ...
Pierre
Peter a écrit :
> Another question, and I really hope this doesn't get emailed four
> idnetical times like my last question. My sincere apologies in advance
> if it does.
>
> I have a C++ class with a virtual function that I want overridden in
> Python. I expose it to Python in the normal way:
>
> class_<MyClass>("CPP_Class", no_init)
> .def("vfunc", &MyClass::func);
>
> And in Python the user derives from this class overrides the virtual
> method, e.g.:
>
> class DerivedClass(CPP_Class):
> def vfunc(self):
> #do stuff in Python
>
> I want to create an instance of "DerivedClass" from C++ and assign it to
> the base class ptr and then call the overridden Python function via the
> virtual fn defined in the C++ base class. So my question is; how do I,
> from C++, create this instance of DerivedClass (assuming I know that the
> user called it DerivedClass)?
>
> Thank you very much for any help,
> Peter
>
>
>
>
>
>
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig
>
--
Pierre Barbier de Reuille
INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France
tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68
More information about the Cplusplus-sig
mailing list