[Numpy-discussion] Looking to access C array in numpy.

Travis E. Oliphant oliphant@enthought....
Tue Jan 22 15:03:54 CST 2008

Travis E. Oliphant wrote:
> Clarke, Trevor wrote:
>> Hash: SHA1
>> I'm calling some python code from a C++ app via an intermediary library
>> (i.e. I can't directly create Python C objects like Buffers). I'm
>> passing a void* (cast to a long) to the python method and I'd like to
>> use numpy to access that memory as an array. I'll know what the C data
>> type is and the minimum length of the data. It's a continuous array but
>> is multiple dimensions (either 2 dimensional or 3 dimensional BIP). I
>> was able to find a may to create an array accessor over a python buffer
>> but I'm not sure how to back an array with a void* (as a long) or create
>> a buffer object for that memory inside python. Could someone point me in
>> the right direction?
> A couple of options that I see:
> 1) Use ctypes to wrap your void* into an object that can be passed into 
> numpy.frombuffer.


res = ctypes.ARRAY(ctypes.c_bytes, 
array = np.frombuffer(res, dtype=mydtype)
> 2) Use the "intentionally not well publicisized function" 
> numpy.core.multiarray.int_asbuffer
res = numpy.core.multiarray.int_asbuffer(void_ptr_as_long, sizeofbuffer, 
readonly=False, check=False)
array = np.frombuffer(res, dtype=mydtype)

Have fun!

-Travis O.

More information about the Numpy-discussion mailing list