如果Data是(c_double*DataLength.value)数组,则可以:a = np.frombuffer(Data) # no copy. Changes in `a` are reflected in `Data`
如果Data是POINTER(c_double),则可以使用^{}获得numpy数组。这与你的问题相同,但速度更快:a = np.fromiter(Data, dtype=np.float, count=DataLength.value) # copy
要在不复制的情况下从POINTER(c_double)实例创建numpy数组,可以使用^{}方法:ArrayType = ctypes.c_double*DataLength.value
addr = ctypes.addressof(Data.contents)
a = np.frombuffer(ArrayType.from_address(addr))
或者array_pointer = ctypes.cast(Data, ctypes.POINTER(ArrayType))
a = np.frombuffer(array_pointer.contents)
两个方法都将POINTER(c_double)实例转换为(c_double*DataLength),然后将其传递给^{}。
基于Cython的解决方案Is there anyway to load the data from the C++ array and then convert it to an array fit for scipy?
下面是Python的C扩展模块(用Cython编写),它将转换函数作为C API提供:cimport numpy as np
np.import_array() # initialize C API to call PyArray_SimpleNewFromData
cdef public api tonumpyarray(double* data, long long size) with gil:
if not (data and size >= 0): raise ValueError
cdef np.npy_intp dims = size
#NOTE: it doesn't take ownership of `data`. You must free `data` yourself
return np.PyArray_SimpleNewFromData(1, &dims, np.NPY_DOUBLE, data)
它可以与ctypes一起使用,如下所示:from ctypes import (PYFUNCTYPE, py_object, POINTER, c_double, c_longlong,
pydll, CFUNCTYPE, c_bool, cdll)
import pointer2ndarray
tonumpyarray = PYFUNCTYPE(py_object, POINTER(c_double), c_longlong)(
("tonumpyarray", pydll.LoadLibrary(pointer2ndarray.__file__)))
@CFUNCTYPE(c_bool, POINTER(c_double), c_longlong)
def callback(data, size):
a = tonumpyarray(data, size)
# call scipy functions on the `a` array here
return True
cpplib = cdll.LoadLibrary("call_callback.so") # your C++ lib goes here
cpplib.call_callback(callback)
其中call_callback是:^{}。