It is relatively simple to call the interface in the DLL file in Python.CodeAs follows:
For example, we have a test. dll file, which is defined as follows:
Extern "C"
{
Int _ stdcall test (void * P, int Len)
{
Return Len;
}
}
In python, we can load data in the following two ways:
1.
Import ctypes
DLL = ctypes. Windll. loadlibrary ('test. dll ')
2.
Import ctypes
DLL = ctypes. Windll ('test. dll ')
Ctypes. Windll is an object of the ctypes. Windll class, which has been defined in the ctypes module. There is a test interface in test. dll, which can be called directly using DLL.
Nrst = DLL. Test ()
Print nrst
Two parameters need to be passed in the test interface. One is a void pointer, which points to a buffer zone. One is the length of the buffer. Therefore, we need to obtain the pointer and length of the string in Python.
# Method 1:
Sbuf = 'aaaaaaaaaabbbbbbbbbbbbbbbbbbbbb'
Pstr = ctypes. c_char_p ()
Pstr. value = sbuf
Pvoid = ctypes. Cast (pstr, ctypes. c_void_p). Value
Nrst = DLL. Test (pvoid, Len (pstr. Value ))
# Method 2:
Test = DLL. Test
Test. argtypes = [ctypes. c_char_p, ctypes. c_int]
Test. restypes = ctypes. c_int
Nrst = test (sbuf, Len (sbuf ))
If you modify the interface definition in test. dll as follows:
Extern "C"
{
Int _ cdecl test (void * P, int Len)
{
Return Len;
}
}
Because the interface defines a call in the cdecl format, the corresponding type must also be used in Python.
1.
Import ctypes
DLL = ctypes. cdll. loadlibrary ('test. dll ')
# Note: The test. o file is generally used in Linux. You can also use the following method:
# DLL = ctypes. cdll. loadlibrary ('test. o ')
2.
Import ctypes
DLL = ctypes. cdll ('test. dll ')
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/lf8289/archive/2008/04/24/2322550.aspx