我可以从python调用dll中的函数。当我调用对我的python代码进行回调的dll函数时,它将失败。是否存在某种互斥体阻止了我的回调?
from ctypes import *
import _ctypes
@CFUNCTYPE(None)
def Test():
print ("Test here")
return
def SetUpDll():
print ("Setting read / write callback functions...")
windll.ClaRUN.AttachThreadToClarion(1)
MyDll = CDLL('IC2_CommsServer.dll')
SetTestFunc = getattr(MyDll, "SETTESTFUNC@Fl")
SetTestFunc (Test)
CallTestFunc = getattr(MyDll, "CALLTESTFUNC@F")
CallTestFunc()
_ctypes.FreeLibrary(MyDll._handle)
_ctypes.FreeLibrary(windll.ClaRUN._handle)
print ("Done.")
SetUpDll()
C:\Users\Derek\anaconda3_32\python.exe Z:/ps_IC2_dll/ps_IC2_dll.py
Setting read / write callback functions...
Traceback (most recent call last):
File "Z:/ps_IC2_dll/ps_IC2_dll.py", line 48, in <module>
SetUpDll()
File "Z:/ps_IC2_dll/ps_IC2_dll.py", line 40, in SetUpDll
CallTestFunc()
OSError: exception: access violation writing 0x009EF77C
Process finished with exit code 1
首先,在Windows上,ctypes使用win32结构化异常处理,以防止在使用无效参数值调用函数时因常规保护错误而导致崩溃。
您对这行代码的调用不好:
CallTestFunc = getattr(MyDll, "CALLTESTFUNC@F")
尝试查看您的代码,然后查看问题是否出在ps_IC2_dll.py构建区域。
感谢CristiFati提供了一半的答案。
此代码现在有效,请注意,clarion dll函数现已原型化为,C一个不错的副作用是函数名称失去了“ @F”后缀,因此代码更简单。
from ctypes import *
import _ctypes
@CFUNCTYPE(None)
def Test():
print ("Test here")
return
def SetUpDll():
print ("Setting read / write callback functions... Ptr=", sizeof(c_void_p), "bytes")
assert sizeof(c_void_p) == 4
ClaRTL = CDLL('./ClaRUN.dll')
MyDll = CDLL('./IC2_CommsServer.dll')
ClaRTL.AttachThreadToClarion.restype = None
ClaRTL.AttachThreadToClarion.argtypes = [c_int32]
ClaRTL.AttachThreadToClarion(1)
MyDll.SETTESTFUNC.restype = None
MyDll.SETTESTFUNC.argtypes = [CFUNCTYPE(None)]
MyDll.SETTESTFUNC (Test)
MyDll.CALLTESTFUNC.restype = None
MyDll.CALLTESTFUNC ()
_ctypes.FreeLibrary(MyDll._handle)
_ctypes.FreeLibrary(ClaRTL._handle)
print ("Done.")
SetUpDll()
现在输出:
C:\Users\Derek\AppData\Local\Programs\Python\Python38-32\python.exe Z:/ps_IC2_dll/ps_IC2_dll.py
Setting read / write callback functions... Ptr= 4 bytes
Test here
Done.
Process finished with exit code 0