Skip to main content
 首页 » 编程设计

Python Numpy 数组 Ctypes 指针

2024年11月01日8java哥

我在 DLL 中有一个 GetImageData 函数:

int GetImageData ( const char * name , int ID , const char * strLibPath , int Lvl , int rbeg , int rend , int cbeg , int cend , int ZLayer , unsigned char * ImgBuffer );  

在 Python 中,我导入这个 DLL 并建立变量:

import ctypes,numpy           
from ctypes import *           
Wlib = ctypes.WinDLL('C:\\...\\Wsl.dll')     
GetImage=Wlib["GetImage"] 
 
name =c_char_p(fname) 
ID =c_int(0) 
strLibPath=c_char_p(LibPath) 
Lvl =c_int(0) 
rbeg =c_int(100) 
rend =c_int(1099) 
cbeg =c_int(5500) 
cend =c_int(6499) 
ZLayer =c_int(0) 
nBpp=24 
nch  = nBpp/8 
roiW = 6499-5500+1 
roiH = 1099-100+1 

在 MATLAB 中定义了一个数组和指针:

img = uint8(zeros([roiW,roiH,nch])); 
ptr = libpointer('uint8Ptr',img); 

在 PYTHON 中,我认为对于 Matlab 等价物应该这样做,但这不起作用并且会杀死 Python:

img = numpy.zeros([roiW,roiH,nch],dtype=ctypes.c_int8) 
ptr=img.ctypes.data_as(ctypes.POINTER(ctypes.c_int8)) 
[status, fname, fpath, img]=GetImage(name,ID,strLibPath,Lvl,rbeg,rend,cbeg,cend,ZLayer, ptr) 

我如何正确地创建一个数组和指针而不是可以提供给我的 DLL?

请您参考如下方法:

手动创建所有 c_int 和 c_char_p 实例是不必要的。但是设置函数指针的 argtypes 以启用类型检查。

NumPy 数组的 ctypes._as_parameter_ 属性是一个 c_void_p。如果您更喜欢更严格的类型安全,请在 argtypes 和 data_as 中使用 POINTER(c_uint8)。

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 

为了方便,我使用 from ctypes import *。您可以将包装的 C API 导入另一个模块以获得干净的命名空间。在 Python 中,一个或多个支持模块和平台模块以首字母下划线命名是很常见的。