关于从加载的DLL调用函数的Python基本问题

2024-06-25 05:22:43 发布

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

我是在搜索和尝试各种各样的例子后提出这个问题的,但我似乎无法从加载的DLL调用函数。我想如果有人能给我举一个例子,我就能理解我做错了什么,并取得一些进展。在

首先,使用Python 3.3.3可以加载DLL,如下所示:

import ctypes
ftdi=ctypes.cdll.LoadLibrary('C:\\Python33\\DLLs\\FTCJTAG.dll')

我可以调用一个不需要任何参数的函数,得到一个有意义的数字。但是,经过多次尝试,我还是不知道如何将参数传递给函数(即指针、字符串、数字)。在

例如,在FTCJTAG.h中,我们有这样一个:

^{pr2}$

从DLL程序员指南:

FTC_STATUS JTAG_GetDllVersion(LPSTR lpDllVersionBuffer, DWORD dwBufferSize)

This function returns the version of this DLL.
Parameters

lpDllVersionBuffer Pointer to the buffer that receives the version of this DLL. 
The string will be NULL terminated.

dwBufferSize Length of the buffer created for the device name string. Set buffer 
length to a minimum of 10 characters.

Return Value

Returns FTC_SUCCESS if successful, otherwise the return value will be one of the
following error codes:

FTC_NULL_DLL_VERSION_BUFFER_POINTER
FTC_DLL_VERSION_BUFFER_TOO_SMALL*

所以,我试试这个:

version_string = ctypes.c_char * 10
string_ptr=version_string()
ftdi.JTAG_GetDllVersion(string_ptr,ctypes.c_long(10))

我把这个拿回来了:

Traceback (most recent call last):
File "C:\Python33\Scripts\FTDI.py", line 5, in <module>
ftdi.JTAG_GetDllVersion(string_ptr,ctypes.c_long(10))
ValueError: Procedure called with not enough arguments (8 bytes missing) or wrong
calling convention

我尝试了很多不同的方法来传递指向函数的指针,或者字符串的长度,但是仍然没有成功。在

有人能提供一个例子,说明如何将这些参数传递给这个函数吗?我确信一旦我看到一个有效的例子,我就可以想出如何调用这个DLL中其余的函数。在

谢谢你的时间!在

编辑:

@Daniel:谢谢您建议使用'windll'而不是'cdll',因为现在上面的函数调用执行得很好。但是,如果我试图调用另一个函数,我会得到一个不同的错误(我也搜索了很久,很难解决):

FTC_STATUS WINAPI JTAG_GetNumDevices(LPDWORD lpdwNumDevices);

要调用此函数,我将执行以下操作:

x = ctypes.c_ulong
x_ptr = x()
ftdi.JTAG_GetNumDevices(x_ptr)

错误是:

Traceback (most recent call last):
File "C:\Python33\Scripts\FTDI.py", line 9, in <module>
ftdi.JTAG_GetNumDevices(x_ptr)
OSError: exception: access violation writing 0x00000000

我得到的结论是,我没有传递指向函数的指针的正确地址,但是经过多次搜索,仍然没有找到答案。我相信这是很简单的事情。:)

再次感谢您的时间!在


Tags: ofthe函数stringversionctypes例子dll