[Numpy-discussion] Pointer to array data for passing to swig-wrapped C++

Angus McMorland amcmorl@gmail....
Mon Aug 24 14:37:24 CDT 2009

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?

Many thanks for your time,

AJC McMorland
Post-doctoral research fellow
Neurobiology, University of Pittsburgh

More information about the NumPy-Discussion mailing list