[C++-sig] Re: Converting a C++ object to python
Raoul Gough
RaoulGough at yahoo.co.uk
Sun Sep 14 13:28:13 CEST 2003
"Ron Penton" <rpenton at adelphia.net> writes:
> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Oh, no! HTML....
>
>
>
> <STYLE></STYLE>
And a complete lack of style, too :-)
>
>
> This has been asked many times, in many variants, but I cannot seem
> to get this working in any shape or form, which leads me to believe
> I'm doing something numbskulled.
>
> I'm trying to perform this sequence of
> events:
> 1 create a C++ object
> 2 convert it into a python object
> 3 pass it into python as a parameter to a
> function
>
>
> Part 2 is the part that is holding me up.
> Observe:
>
> class booga{public:
> booga() : a( 0 ) {} int a; void
> looga() { a = a + 10; cout << a << endl; }};
> BOOST_PYTHON_MODULE( wrap ){ class_<booga>( "booga"
> ) .def( "looga", &booga::looga
> );}
> int main(){ Py_Initialize();
>
> PyImport_AppendInittab(
> "wrap", initwrap );
> booga b;
> object obj( &b );
>
> That last line of code always throws an exception of type
> error_already_set, from within the function "value_arg_to_python".
If you catch a boost::python::error_already_set in C++, I guess you
can get more information by calling PyErr_Print(), which should dump a
standard Python traceback on stderr. At a guess, you're getting a
Python TypeError from the object constructor, because it doesn't have
a converter for booga *. BTW, why are you passing a pointer to b,
instead of a reference?
>
> My thoughts are that I am missing something about a custom
> converter, or similar, but I've read through the converter docs and
> I'm quite baffled; they don't explain much. Would the
> BOOST_PYTHON_MODULE create a custom converter for classes in there,
> or must I specify one manually, or what?
I don't have any experience embedding Python in C++, because I work
the other way around (i.e. using C++ extensions from within Python).
However, the documentation for PyImport_AppendInittab says that you
should call it *before* Py_Initialize. I would have thought you want a
normal import of your module anyway, rather than trying to make it act
like a built-in.
--
Raoul Gough.
(setq dabbrev-case-fold-search nil)
More information about the Cplusplus-sig
mailing list