Python ctypes:OSError:exception:访问冲突写入0x00000000

2024-09-29 19:18:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用ctypes调用由C构建的dll中的函数。我在输入类型方面遇到了问题,因此发生了操作系统错误。 dll的C代码中的函数参数:

DllExport extern double far pascal dFlComprOil (
   int               nOilCompr,    
   double            dOilGrav,    
   double            dSGGas,       
   double            dSolnGOR,     
   double            dTargetPress, 
   double            dTargetTemp,  
   double            dSepPress,     
   double            dSepTemp,     
   BOOL              bCheckRanges, 
   char          far szErrorMsg[], 
   int           far *nError) 

还有我的Python代码:

from ctypes import *
lib = WinDLL(r"C:\FldSP970.dll")
class SomeStructure(Structure):
    _fields_ = [
    ('nOilCompr', c_int),
    ('dOilGrav', c_double),
    ('dSGGas', c_double),
    ('dSolnGOR', c_double),
    ('dTargetPress', c_double),
    ('dTargetTemp', c_double),
    ('dSepPress', c_double),
    ('dSepTemp', c_double),
    ('bCheckRanges', c_bool),
    ('szErrorMsg[]', c_char),
    ('*nError', c_int)
    ]
lib.dFlComprOil.restype = c_double
lib.dFlComprOil.argtypes = [POINTER(SomeStructure)]
#lib.dFlComprOil.argtypes = c_int,c_double,c_double,c_double,c_double,c_double,c_double,c_double,c_bool,c_char,c_int      
s_obj = SomeStructure(0, 35, 0.65, 151.489, 861.066, 60, 100, 60,False,0,0)
result = lib.dFlComprOil(byref(s_obj))

我已经修复了一些错误,并对参数szerrmsg进行了实验,但它最终给出了这个模糊的操作系统错误。我猜我在最后两个参数上做错了什么,但是由于我对C不太熟悉,我现在迷路了。任何帮助或指导都将不胜感激


Tags: 代码lib错误ctypesintdlldoublefar
1条回答
网友
1楼 · 发布于 2024-09-29 19:18:24

不要使用结构。C调用中没有结构。使用argtypes,但上一个参数错误:

from ctypes import *
lib = WinDLL(r"C:\FldSP970.dll")
lib.dFlComprOil.argtypes = c_int,c_double,c_double,c_double,c_double,c_double,c_double,c_double,c_bool,c_char_p,POINTER(c_int)
lib.dFlComprOil.restype = c_double
# Likely the last two parameters are output values, so allocate some amount of storage.
# Consult the function documentation...the size requirements aren't obvious.
errmsg = create_string_buffer(1024)  # equivalent to char[1024];
nerror = c_int()                     # A single C integer for output.
result = lib.dFlComprOil(0, 35, 0.65, 151.489, 861.066, 60, 100, 60,False,errmsg,byref(nerror))

相关问题 更多 >

    热门问题