开发者

Create numpy array from C-ptr aquired via ctypes

I have allocated a chunk of double in a C library and I would like to create a numpy 1D array based on that data; ideally I would like two versions one which only wraps the c_ptr readonly - letting the C layer retain ownership of the data, and one which copies the data. So simplified code would be like this:

C-code

double * init_and_alloc( size_t size ) {  
  double * ptr = malloc( size * sizeof * ptr );
  // initialize ptr  
  return ptr;  
}  

Python code

size = 1000 
c_ptr = ctypes_func_ptr_init_and_alloc( size )  
numpy_array = numpy.xxxx( c_ptr , size , dtype.flo开发者_运维知识库at64) <--- ?????

So does the function I have labelled xxxx exist?

Best Regards

Joakim Hove


Yes, numpy.ctypeslib.as_array To get a given dtype, as_array(ptr, shape).view(dtype).

This should work, at least in theory (don't have time to test it now).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜