[C++-sig] Wrapping already constructed c++ objects.

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Mon Jul 11 16:44:26 CEST 2005


Well, what to do depend where and when you want to put your object ^_^

Simplest: if you want to add it to your module at import time !

You just have to use the scope object :

   scope current;

Then, you can add objects in it :

   current.attr("foo") = object(Foo());

(see : http://www.boost.org/libs/python/doc/v2/scope.html for details).

To add the object at runtime, you have to get the __main__ module :

object main_module = object(handle<>(PyImport_AddModule("__main__")));
dict main_namespace = extract<dict>( object( handle<>( PyModule_GetDict(
main_module.ptr()))));

Then, you can add objects directly in the dictionnary of the __main__
module :

   main_namespace["foo"] = object(Foo());

Pierre

Shahrouz Zolfaghari a écrit :
> Hello,
> 
> I would like to know if it is possible to use boost.python to wrap an
> already created c++ object and make it available though the embedded
> python interpreter?
> 
> So the instance "foo" the class "Foo" should be exposed to the python
> interpreter as a module.
> 
> Here is a little example with the wrapping manually done, using Python/C api:
> 
> class Foo
> {
> public:
>         void method() { ... }
> };
> 
> Foo foo;
> 
> PyObject * foo_method_wrap(PyObject *self,PyObject * argv)
> {
>         foo.method();
>         return Py_None;
> }
> 
> static PyMethodDef foo_methods[] = {
>     {"method",  foo_method_wrap, METH_VARARGS, "Call foo.method()."},
>     {NULL, NULL, 0, NULL}
> };
> 
> int main()
> {
>         Py_Initialize();
>         Py_InitModule("foo",foo_methods);
>         PyRun_SimpleString( "import foo\n"
>                             "foo.method()\n");
>         Py_Finalize();
> }
> 
> Thanks,
> Eracce
> 
> _______________________________________________
> 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