Manually creating all the c_int
and c_char_p
instances is unnecessary. But set the function pointer's argtypes
to enable type checking.
The ctypes._as_parameter_
attribute of NumPy arrays is a c_void_p
. If you prefer more strict type safety, use POINTER(c_uint8)
in argtypes
and data_as
.
from ctypes import *
import numpy as np
__all__ = ['GetImage']
# WinDLL is stdcall; use CDLL for cdecl.
Wlib = WinDLL(r'C:\...\Wsl.dll')
Wlib.GetImage.argtypes = ([c_char_p, c_int, c_char_p] +
[c_int] * 6 +
[c_void_p])
def GetImage(name, ID, strLibPath, Lvl=0,
rbeg=100, rend=1099,
cbeg=5500, cend=6499,
ZLayer=0, nBpp=24):
roiW = cend - cbeg + 1
roiH = rend - rbeg + 1
nch = nBpp // 8
img = np.zeros([roiW, roiH, nch], dtype=np.uint8)
ImgBuffer = img.ctypes
status = Wlib.GetImage(name, ID, strLibPath, Lvl,
rbeg, rend, cbeg, cend,
ZLayer, ImgBuffer)
# test status
return img
I use from ctypes import *
for convenience. You can import the wrapped C API into another module to get a clean namespace. It's common in Python to have one or more support modules and platform modules named with an initial underscore.