[C++-sig] Conversion problem

Simon Pickles sipickles at googlemail.com
Wed Jan 13 10:00:54 CET 2010


Hello,

I wonder if someone could help me with a tricky conversion between c++ 
and python types (well, tricky for me!)

I have a c++ library that I would like to use in python via Boost::Python

One function fills a c++ unsigned char* buffer. It has two overloads:

        unsigned char * getPixels(int deviceID);
        bool getPixels(int id, unsigned char * pixels);

How would I go about getting that data into a python object, a string in 
particular? I seem to face several problems:
/////////////////////////
1) unsigned char* does not have a to_python converter to Py_String.

I tried this:

struct uchar_ptr_to_str
{
    static PyObject* convert(unsigned char* p)
    {
         return incref( str(p).ptr());
    }
    static PyTypeObject const *get_pytype () {return &PyString_Type; }
};
struct uchar_to_str
{
    static PyObject* convert(unsigned char& p)
    {
         return incref( str(p).ptr());
    }
    static PyTypeObject const *get_pytype () {return &PyString_Type; }
};

BOOST_PYTHON_MODULE(pyVideoInput)
{
    to_python_converter< unsigned char*, uchar_ptr_to_str, true >();   
    to_python_converter< unsigned char, uchar_to_str, true >();

    class_<videoInput>("videoInput")
       .def("getPixels", &videoInput::getPixels, 
return_value_policy<manage_new_object>())
       ;
}


/////////////////////////
2) How do I allocate memory in a python string and then pass the pointer 
through boost python, to be filled by the c++ function?

In c++, the library would be used like this:

    videoInput vi;
    ....
    unsigned char * buffer = new unsigned char[size];
    vi.getPixels(device, buffer);

The buffer could be pretty big so I want to pass by pointer, not by value

The alternative would be to use the overload which returns the pointer, 
but I can't get that to compile with bjam. I get the dreaded:

make_instance.hpp(24) : error C2027: 
use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>

when I try to return a pointer...

Thanks for any help freeing me from my confusion!

Regards

Si







More information about the Cplusplus-sig mailing list