Python回调因访问冲突而失败

2024-05-03 05:46:56 发布

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

我可以从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

Tags: 函数pytestimportreaddefctypessetting
2条回答

感谢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

首先,在Windows上,ctypes使用win32结构化异常处理,以防止在使用无效参数值调用函数时因常规保护故障而崩溃

您对这行代码的调用不正确:

CallTestFunc = getattr(MyDll, "CALLTESTFUNC@F")

尝试检查代码,然后查看问题是否来自ps\u IC2\u dll.py构建区域

相关问题 更多 >