python使用ctypes调用dll

因为 ctypes 是内置模块,可以直接使用:

from ctypes import *

加载dll程序

from ctypes import *
dll = CDLL('./test-sdk.dll')

调用dll方法

直接调用:

from ctypes import *
dll = CDLL('./test-sdk.dll')
dll.test_method()

传递 数字 参数:

from ctypes import *
dll = CDLL('./test-sdk.dll')
dll.test_method(1)

传递 数组 参数:

from ctypes import *
dll = CDLL('./test-sdk.dll')

class Rect(Structure):
    _fields_ = [('x1', c_short), ('y1', c_short), ('x2', c_short), ('y2', c_short)]

rois = (Rect * 5)()
rois[0] = Rect(16, 16, 32, 32)
rois[1] = Rect(64, 64, 128, 128)
dll.test_method(rois)

传递 指针 参数:

from ctypes import *
dll = CDLL('./test-sdk.dll')

context_id = c_int(0)
dll.test_method(byref(context_id))
print(context_id.value)

传递 自定义的数据类型 参数:

from ctypes import *
dll = CDLL('./test-sdk.dll')

class Point2f(Structure):
    _fields_ = [('x', c_float), ('y', c_float)]

class ROI(Structure):
    _fields_ = [('number', c_int), ('points', Point2f)]

dll.test_method(ROI(1, Point2f(0.21, 0.43)))

传递 数组指针 参数:

from ctypes import *
dll = CDLL('./test-sdk.dll')

class Rect(Structure):
    _fields_ = [('x1', c_short), ('y1', c_short), ('x2', c_short), ('y2', c_short)]

class RectInfo(Structure):
    _fields_ = [('rect_nums', c_int), ('rects', (Rect*5))]

output = (RectInfo*5)()
dll.test_method(byref(output))

传递 numpy.ndarray 参数:

import numpy as np
from ctypes import *
dll = CDLL('./test-sdk.dll')

# 造一个 uchar BGR 高*宽*3ch 的空数组
frame = np.empty((360, 640, 3))
# numpy.ndarray -> ctypes.c_char_p
enter_frame = c_char_p(frame.tobytes())
dll.test_method(enter_frame)
# ctypes.c_char_p -> numpy.ndarray
output_frame = np.ctypeslib.as_array(POINTER(c_ubyte).from_address(addressof(enter_frame)), shape=frame.shape)

# 保存图片, 检查 ctypes.c_char_p -> numpy.ndarray 结果
import cv2
cv2.imwrite('save_img.bmp', output_frame)

# 转换回的数据可能无法在函数间传递, 需要重新写一遍
return_frame = np.array(output_frame)

猜你喜欢

转载自blog.csdn.net/hekaiyou/article/details/125284624