使用ctypes传递numpy数组到C++ dll输出异常该如何解决?
问题解决方法
核心根因
你目前的数值不匹配问题主要来自两个错误:
- 类型不匹配:numpy的
np.float实际对应C的double(双精度浮点数,8字节),但你C函数接收的是float*(单精度浮点数,4字节),内存读取长度不一致自然得到错误数值。 - 内存连续性问题:numpy数组经过切片、转置等操作后会变成非连续存储,直接传递内存指针会导致C++读取的地址偏移错位。
C++端修改
需要添加extern "C"避免C++编译器对函数名做修饰,导致ctypes找不到导出函数:
extern "C" __declspec(dllexport) void image(const float* img, int m, int n) { for (int i = 0; i < m * n; i++) { printf("%f ", img[i]); } }
注意编译DLL时VS必须选择x64配置,和你使用的64位Python环境位数匹配。
Python端修改
需要显式指定数组为单精度浮点数,同时保证数组内存连续:
import ctypes import numpy as np lib = ctypes.cdll.LoadLibrary("./bin/Release/dllAPI.dll") lib.image.argtypes = (ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int) lib.image.restype = None img = np.random.random(size=[3, 3])*10 # 显式转换为float32,对应C++的float类型 img = img.astype(np.float32) # 保证数组是连续内存存储,避免读取错位 img_contiguous = np.ascontiguousarray(img) print('c++ result is: ') img_p = img_contiguous.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) lib.image(img_p, 3, 3) print('\n original data is:') print(img)
补充说明
如果你想保留双精度计算,只需两边类型同步修改即可:
- C++端参数改为
double* img,printf格式符改为%lf - Python端数组转
np.float64,argtypes改为ctypes.POINTER(ctypes.c_double)
内容的提问来源于stack exchange,提问作者Qiang Zhang
相关产品推荐
相关产品推荐

