[Numpy-discussion] Pointer to array data for passing to swig-wrapped C++
Mon Aug 24 14:47:47 CDT 2009
On Mon, Aug 24, 2009 at 12:37, Angus McMorland<firstname.lastname@example.org> wrote:
> Hi all,
> Our lab has an in-house messaging protocol, written in C++, for
> interfacing the different components of our experimental setups, and
> allowing programs written in several different languages to talk to
> each other. I'm currently trying to write a Python interface to this
> protocol, mainly so I can show people here how good a Traits-based GUI
> would be for controlling things. I'm not familiar with interfacing C++
> and Python code, so this is a little hit and miss, and any suggestions
> on better approaches would be welcome. I have wrapped the C++ code in
> swig, and can now call the simple routines from within Python.
> The trouble I'm having is constructing new message data, and passing a
> reference to that data. Each message consists of a ID code telling us
> what type of message it is, a buffer of data, of which some subset is
> actually useful, and the number of bytes of the buffer that have been
> filled with useful data. I can get message data out of a message
> constructed and sent by some other implementation of the protocol by
> reading it into a numpy array with a dtype matching the structure of
> the data being sent, and calling, for example:
> np.fromstring(msg_data[0:num_bytes], dtype=[('a', int),('b', float)])
> I can't work out how to do the reverse operation: to populate the C++
> message object with data constructed in Python. The message object has
> a SetData function,which is exposed by swig, that requires a 'void *'
> pointer to the data (as well as the number of bytes being sent), and I
> thought I might be able to do something like:
> msg.SetData(array.data, array.nbytes)
> where array is another ndarray of the desired dtype, but that returns the error:
> TypeError: in method 'CMessage_SetData', argument 2 of type 'void *'
> and using array.tostring() in place of array.data above gives exactly
> the same result. Is there a convenient syntax to pass a void * pointer
> to the array's data to the swig-wrapped SetData routine, or do I have
> to write some extra wrapping code to make this happen, and what might
> that code look like roughly?
You will need an extra typemap on SetData() to make it accept a char*
on the Python side (which can be supplied as a string or preferably a
buffer object) and cast it to a void*. Someone with more recent SWIG
experience or the SWIG docs will have to tell you how to do that,
though. It should be straightforward, though.
"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
More information about the NumPy-Discussion