The example in this article describes Python's method of referencing DLL files. Share to everyone for your reference. The specific analysis is as follows:
Calling the interface in a DLL file in Python is simpler, as we have a Test.dll file, which is internally defined as follows:
?
1 2 3 4 5 6 7 |
extern "C" {int __stdcall Test (void* p, int len) {return len;}} |
In Python we can load in the following two ways
1.
?
1 2 |
Import cTYPES DLL = ctypes.windll.LoadLibrary (' Test.dll ') |
2.
?
1 2 |
Import ctypes dll = cTYPES. Windll (' Test.dll ') |
Where Ctypes.windll is an object of the Ctypes.windll class, it has been defined in the cTYPES module. There is a test interface in Test.dll that can be invoked directly with a DLL
?
1 2 |
Nrst = Dll.test () print Nrst |
Because two parameters need to be passed in the test interface, one is a pointer of type void, which points to a buffer. One is the length of the buffer. So we're going to get the pointer and the length of the string in Python
?
1 2 3 4 5 6 |
#方法一: sbuf = ' aaaaaaaaaabbbbbbbbbbbbbb ' pstr = ctypes.c_char_p () Pstr.value = Sbuf pvoid = Ctypes.cast (PStr, Ctypes.c_vo id_p). Value Nrst = Dll.test (pvoid, Len (pstr.value)) |
?
1 2 3 4 5 |
#方法二: test = dll.test Test.argtypes = [Ctypes.c_char_p, ctypes.c_int] test.restypes = ctypes.c_int nrst = Test (SBuf, Len (s BUF)) |
If you modify the interface in Test.dll, the definition is as follows:
?
1 2 3 4 5 6 7 |
extern "C" {int __cdecl test (void* p, int len) {return len;}} |
Because the interfaces are defined in CDECL format calls, the corresponding type is also required in Python
1.
?
1 2 3 4 |
Import cTYPES DLL = ctypes.cdll.LoadLibrary (' Test.dll ') # #注: Generally under Linux for TEST.O files, you can also use the following methods: # #dll = Ctypes.cdll.LoadLibrary (' TEST.O ') |
2.
?
1 2 |
Import ctypes dll = cTYPES. Cdll (' Test.dll ') |
I hope this article will help you with your Python programming.