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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何小有

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值