[C++-sig] Re: Conversion of C++ return type.

Hanz Meizer steam at nurfuerspam.de
Wed Mar 3 16:46:51 CET 2004


> Good guess.
> 
> Unfortunately I can't track down the details for you, but here's the
> gist: you need to register a custom to_python_converter for Any.
> Then, inside its conversion function, you need to get the typeid of
> the type stored by the Any (if you can't get that you're out of luck),
> and invoke the registry's lookup function to get the to-python
> conversion chain for the stored type.  Then you need to "manually"
> invoke that converter. Expect the resulting code to be fairly ugly
> and low-level.  Sorry :(
> 
> 

The Any objects usually contain very basic types, or vectors of very 
basic types. So I think what would be really nice is to have two 
functions, one converting an Any object to a PyObject that contains a 
pythonification of the Any member objects, and another one that gets 
called with a python object and returns the corresponding Any object. 
The latter would be used implicitly when a C++ Method is called from 
python (for example std::string printAny(const Any& car) ).

For example:
I have a function Any* getProperty() that returns an Any that either 
conains a vector<double> or a single double. The conversion function 
then would take the Any, and return a PyObject to python that either 
contins a list of doubles or a simple double.

Unfortunately, diggig through the examples and mailing list archives 
didn't enlighten me enough, my last test was something like:

namespace
{
   struct any_to_python
   {
     static PyObject* convert(Any const& x)
     {
       std:cerr << "convert called, rejoice!" << endl;
       exit(1);
     }
};

...

class_< Any, boost::noncopyable >("Any", no_init)
;

to_python_converter< Any, any_to_python >();

The intention is to have any_to_python::convert check what is inside of 
the Any and return the approprioate, constructed python object. 
Unfortunately, convert is never called. If I uncomment the class_<> ...; 
thing, python says:

No Python class registered for C++ class Any

If I sue the class_<>...; thing, I get some error because python tries 
to call __str__ on the Any object and fails. Help! :)

Regards,
H.





More information about the Cplusplus-sig mailing list