python类型如何转换为指针_如何将指向c数组的指针转换为python数组

如果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是:^{}。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值