[英]ctypes: pass numpy to c++ dll
我使用 C++ 来实现一个 dll,并使用 python 来使用它。 当我将一个numpy传递给dll时,报告了一个错误
我的 C++ 代码是:
__declspec(dllexport) void image(float * img, int m, int n)
{
for (int i = 0; i < m*n; i++)
{
printf("%d ", img[i]);
}
}
在上面的代码中,我只是传递了一个 numpy,然后打印出来。
然后,我使用这个 dll 的 python 代码是:
import ctypes
import numpy as np
lib = ctypes.cdll.LoadLibrary("./bin/Release/dllAPI.dll")
img = np.random.random(size=[3, 3])*10
img = img.astype(np.float)
img_p = img.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
lib.image.argtypes = (ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int)
lib.image.restype = None
print('c++ result is: ')
lib.image(img_p, 3, 3)
print('\n original data is:')
print(img)
打印的信息是:
c++ result is:
-536870912 -1073741824 0 1610612736 -1073741824 1073741824 1610612736 536870912 -2147483648
original data is:
[[7.76128455 3.16101652 7.44757958]
[2.32058998 9.96955139 3.26344099]
[9.42976627 1.34360611 8.4006054 ]]
我的C++代码打印了一个随机数,看起来内存泄漏了。
我的环境是:
win 10
vs 2015 x64
python 3.7
ctypes 1.1.0
如何通过ctypes
将 numpy 传递给 C++? 任何建议表示赞赏~~~
- - - - - - - - - 更新 - - - - - - - - - - -
C++ 代码有一个printf
错误,我将 C++ 代码更新为:
__declspec(dllexport) void image(float * img, int m, int n)
{
for (int i = 0; i < m*n; i++)
{
printf("%f ", img[i]);
}
}
但是打印出来的信息还是不正确:
c++ result is:
12425670907412733350375273403699429376.000000 2.468873 0.000000 2.502769 4435260031901892608.000000 2.458449 -0.000000 2.416936 -4312230798506823897841664.000000
original data is:
[[7.50196262 8.08859399 7.33518741]
[6.67098506 0.04736352 9.5017838 ]
[3.47544102 9.09726041 0.48091646]]
因此,经过一番挖掘,我发现显然numpy.float
,实际上等效于ctypes.c_double
(?),您应该执行img.astype(ctypes.c_float)
,以便指针指向有效结果。 我不知道为什么np.float
会是 64 位浮点数,但从我的调试中我看到了。 如果你想重现这个尝试在 python 中打印img_p[0]
来查看。
注意:在这种情况下使用特定的强制转换可能是最佳实践,因为不同的 dtype 可能是实现定义的,导致这个确切的错误(即使两者都是float
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.