KDEV
KDEV

Reputation: 63

How to convert unsigned char* to Python list using Swig?

I have a C++ class method like this:

class BinaryData
{
public:
    ...
    void serialize(unsigned char* buf) const;
};

serialize function just get binary data as unsigned char*. I use SWIG to wrap this class. I want to read binary data as byte array or int array in python.

Python Code:

buf = [1] * 1000;
binData.serialize(buf);

But it occurs exception that can't convert to unsigned char*. How can I call this function in python?

Upvotes: 0

Views: 521

Answers (1)

Simplest thing to do is to convert it inside Python:

buf = [1] * 1000;
binData.serialize(''.join(buf));

Will work out of the box, but is potentially inelegant depending on what Python users are expecting. You can workaround that using SWIG either inside Python code, e.g. with:

%feature("shadow") BinaryData::serialize(unsigned char *) %{
def serialize(*args):
    #do something before
    args = (args[0], ''.join(args[1]))
    $action
    #do something after
%}

Or inside the generated interface code, e.g. using buffers protocol:

%typemap(in) unsigned char *buf %{
    //    use PyObject_CheckBuffer and
    //    PyObject_GetBuffer to work with the underlying buffer
    // AND/OR
    //    use PyIter_Check and
    //    PyObject_GetIter
%}

Where you prefer to do this is a personal choice based on your preferred programming language and other situation specific constraints.

Upvotes: 1

Related Questions