如何解决Python ctypes:OSError:异常:访问冲突写入0x00000000
我正在尝试使用 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',('dSolnGOR',('dTargetPress',('dTargetTemp',('dSepPress',('dSepTemp',('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_bool,c_char,c_int
s_obj = SomeStructure(0,35,0.65,151.489,861.066,60,100,False,0)
result = lib.dFlComprOil(byref(s_obj))
我已经修复了一些错误并为参数 szErrorMsg 做了实验,但它最终给出了这个模糊的操作系统错误。我猜我在最后两个参数上做错了什么,但由于我不太熟悉 C,我现在迷路了。任何帮助或指导将不胜感激。
解决方法
不要使用结构。 C 调用中没有结构。使用 argtypes,但你的最后一个参数是错误的:
from ctypes import *
lib = WinDLL(r"C:\FldSP970.dll")
lib.dFlComprOil.argtypes = c_int,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,False,errmsg,byref(nerror))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。