[C++-sig] Re: Howto build a Boost.Python object that wraps a C++ class

David Abrahams dave at boost-consulting.com
Tue Oct 7 01:52:14 CEST 2003


"Guillermo Narvaja" <guillon at myrealbox.com> writes:

> Hi, I'm new using Boost.Python. I ask for help with the following trouble:
>
> I want to build a Python object that wraps a C++ class with an instance of
> that class. Here is the code of what I tried...
>
> I define a Python Module like this:
>
> BOOST_PYTHON_MODULE(test)
> {
> 	class_<Widget>( "Widget", init<int>() )
> 		.def( init<const Widget &>() )
> 		.def( "doSomething", &Widget::doSomething );
> }
>
>>From another module(.exe), I want to embed python code (in this example, a
> function that receives 2 widgets and returns an int). I tried the following:
>
> // Imports a module with a function that receives 2 widgets
> object module( handle<>( PyImport_Import( boost::python::str(
> "module_with_widgetfn" ).ptr() ) ) );
> object test_module( handle<>( PyImport_Import( boost::python::str(
> "test" ).ptr() ) ) );
> // Get dictionaries from those modules
> dict moduleDict( boost::python::detail::borrowed_reference(
> PyModule_GetDict( module.ptr() ) ) );
> dict testModuleDict( boost::python::detail::borrowed_reference(
> PyModule_GetDict( test_module.ptr() ) ) );

> object fnFoo = moduleDict.get( "foo" ); // Get the foo function object
> object Widget_class = testModuleDict.get( "Widget" ); // To get the foo

Why bother with that?

  object fnFoo = module.attr("foo");
  object Widget_class = testModule.attr("Widget");

is cleaner and simpler.

> class
> object aPy( Widget_class( 1 ) ); // works
> Widget b( 1 );
> object bPy( Widget_class( b ) ); // ---->>DOESN'T WORKS, throws
> error_already_set

error_already_set corresponds to some Python exception.  Which Python
exception is being raised?  libs/python/test/embedding.cpp shows how
to report that exception.

> int result = call< int >( fnFoo.ptr(), aPy, bPy );

  int result = extract<int>(fnFoo(aPy,bPy));

Works too.
-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list