[C++-sig] How to use own C++/python bindings in embeddedinterpreter.

Stefan Seefeld seefeld at sympatico.ca
Mon Jan 22 20:27:10 CET 2007


Pierre Bourgault wrote:

> That allows me to have a python script that does this:
> ------------------------------------------------------
> # useMyClass.py
> import whatever
> a = new MyClass()

surely the 'new' is a typo here ? :-)

> a.doit()
> 
> ==================================================================
> 
> Now I want to call func() defined in scriptWithFunc.py from C++, 
> passing it a python instance of MyClass, but created first in C++:
> # scriptWithFunc.py
> import whatever
> def func(myobj):
>    myobj.doit()
> 
> SOLUTION: The C++ code that calls func():
> -----------------------------------------
> 
> // callScriptFunc.cpp
> // 
> str script = "scriptWithFunc";
> str function = "func";
> object moduleWithFunc = PyImport_Import(script);

With current boost.python code that becomes

object moduleWithFunc = boost::python::import(script);

> object func = PyObject_GetAttrSring( moduleWithFunc, function );

object func = moduleWithFunc.attr("__dict__")[function]

> if (!(func && PyCallable_Check(func))) { 
>    return;
> }
> 
> // import module "whatever"
> handle<> module(PyImport_Import("whatever")); 
> object theModule(handle<>(borrowed(PyImport_AddModule("whatever"))));
> // Obtain its dictionary and get the object representing class MyClass.
> dict d = extract<dict>(dict(theModule.attr("__dict__"));

dict d = theModule.attr("__dict__");

should work just fine.


> object MyClass_Class = d[ 'MyClass' ]

object MyClass_Class = d["MyClass"];

> 
> // Create an instance
> myObj = MyClass_Class()
> 
> PyTuple_SetItem(args, myObj.ptr());
> PyObject_CallObject(function, args);

func(myObj);

should work just fine.


HTH,
		Stefan

-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list