所以我正在使用 django 开发后端,并且我得到了一个图像处理步骤,我使用我公司开发的私有 c++ .dll。 我正在使用 ctypes 加载 .dll 文件并设法使一些导入的函数正常工作。但某些功能(本例中为“fr_get_fire_img”)无法按预期工作。 我不知道我是否指定了函数的 argtypes 或者函数的 restype 不正确,需要一些指导,提前致谢!
这是c#中的函数签名:
[DllImport(DLL_NAME)]
public static extern IntPtr fr_get_fire_img(byte instance, ref short W, ref short H, ref short step);
这是我尝试使用导入函数的Python代码:
import ctypes
from ctypes import c_char_p as char_pointer
from ctypes import c_short as short
from ctypes import c_void_p as int_pointer
zero = char_pointer(0)
w = short(0)
h = short(0)
step = short(0)
fire_dll.fr_get_fire_img.restype = int_pointer
source = fire_dll.fr_get_fire_img(zero, w, h, step)
print(source, type(source))
最后这是我从 ctypes 得到的错误:
Traceback (most recent call last):
File "PATH OF PYTHON FILE", line 44, in <module>
source = fire_dll.fr_get_fire_img(zero, w, h, step)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OSError: exception: access violation writing 0x0000000000000000
我在网上找不到任何参考资料,因此我希望获得一些帮助或指导。
在一切之前,请检查[SO]:通过 ctypes 从 Python 调用的 C 函数返回不正确的值(@CristiFati 的答案),了解使用 CTypes(调用函数)时的常见陷阱。
如果你的 C# 函数头是正确的,那么它在 Python 中应该是这样的(尽管 byte 类型的 instance 和 0 值对我来说看起来不正确):
import ctypes as cts
# ...
IntPtr = cts.POINTER(cts.c_int)
ShortPtr = cts.POINTER(cts.c_short)
fr_get_fire_img = fire_dll.fr_get_fire_img
fr_get_fire_img.argtypes = (cts.c_ubyte, ShortPtr, ShortPtr, ShortPtr)
fr_get_fire_img.restype = cts.c_void_p # @TODO: C#
instance = 0
h = cts.c_short(0)
w = cts.c_short(0)
step = cts.c_short(0)
res = fr_get_fire_img(instance, cts.byref(w), cts.byref(h), cts.byref(step))
# ...