我已经多次尝试使用结构作为参数调用DLL函数,但没有一个成功。我使用的是Python 2.7.8。这是我的代码:
from ctypes import c_int, c_bool, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT, sizeof
INPUT_PARM, OUTPUT_PARAM, INPUT_PARM_DEFAULT_ZERO = 1, 2, 4
prototype = WINFUNCTYPE(c_int, c_int, LPCSTR, LPCSTR, c_bool)
paramflags = ((INPUT_PARM, "Size", 0),
(INPUT_PARM, "ProgrammerExe", r"C:\Program Files (x86)\ChipProgUSB\6_00_05\UprogNT2.exe"),
(INPUT_PARM, "CommandLine", "/m"),
(INPUT_PARM, "DebugMode", True))
Programmer = prototype(("ACI_Launch", windll.ACI), paramflags)
Programmer()
这是我正在进行的DLL调用的文档:
ACI_FUNC ACI_Launch(ACI_Launch_Params * params);
typedef struct tagACI_Launch_Params
{
UINT Size; // (in) Size of structure, in bytes
LPCSTR ProgrammerExe; // (in) Programmer executable file name
LPCSTR CommandLine; // (in) Optional programmer command-line parameters
BOOL DebugMode; // (in) Debug mode. Programmer window is not hidden
} ACI_Launch_Params;
错误是异常:访问冲突读取0x00000000 这看起来像是尝试使用Size作为指针,当我删除Size参数时,它的部分如下所示:
prototype = WINFUNCTYPE(c_int, LPCSTR, LPCSTR, c_bool)
paramflags = ((INPUT_PARM, "ProgrammerExe", ...
然后它给出:过程可能用太多的参数调用(超过8个字节)
该DLL可从phyton.com获得,作为演示。如果您查看硬件页面的底部,则有一个不需要任何注册的链接。
更新:在eryksun的帮助下,我解决了我的大错。但我仍然有一个问题,我现在不知道如何解决:
from ctypes import c_int, c_bool, WINFUNCTYPE, windll, Structure,POINTER, c_void_p
from ctypes.wintypes import HWND, LPCSTR, UINT, sizeof, HRESULT
class ACI_Launch_Params(Structure):
_fields_ = [("Size" , c_int),
("ProgrammerExe" , LPCSTR ),
("CommandLine" , LPCSTR ),
("DebugMode" , c_bool ),
]
x=ACI_Launch_Params(64,r"C:\Program Files (x86)\ChipProgUSB\6_00_05\UprogNT2.exe","/m",False)
Launch = windll.ACI.ACI_Launch
Launch.argtypes = [POINTER(ACI_Launch_Params)]
Launch.restype = HRESULT
Exit = windll.ACI.ACI_Exit
Exit.argtypes = []
Exit.restype = HRESULT
print "start result",Launch(x)
time.sleep(4)
# prints Added for Debugging
print sizeof(x),x #OK
print x.Size #OK
print x._objects #OK
print x.__sizeof__() #Crash
print dir(x) #Crash
print x.__dict__ #Crash
del x #Crash
print "stop result",Exit()
time.sleep(3)
这始终按预期启动应用程序,并且打印的返回值为0.但是在退出python代码时,它会崩溃python.exe。它似乎与结构“x'被删除,如果我之前删除它,那么它会在那时崩溃。我猜测DLL正在释放结构,但如果是这种情况,我该如何才能可靠地运行?
事件记录器报告:
Faulting application name: python.exe, version: 0.0.0.0, time stamp: 0x53b1ecd8
Faulting module name: python27.dll, version: 2.7.8150.1013, time stamp: 0x53b1ecd6
Exception code: 0xc0000005
Fault offset: 0x00031fe5
Faulting process id: 0x62d8