Using python to reference DLL files,
This example describes how to reference a DLL file in python. Share it with you for your reference. The specific analysis is as follows:
Calling the interface in the dll file in python is relatively simple. 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 ctypesdll = ctypes.windll.LoadLibrary( 'test.dll' )
2.
import ctypesdll = 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 = 'aaaaaaaaaabbbbbbbbbbbbbbbbb' pStr = ctypes. c_char_p () pStr. value = sBufpVoid = ctypes. cast (pStr, ctypes. c_void_p ). valuenRst = dll. test (pVoid, len (pStr. value ))
# Method 2: test = dll. testtest. argtypes = [ctypes. c_char_p, ctypes. c_int] test. restypes = ctypes. c_intnRst = 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 ctypesdll = ctypes. cdll. loadLibrary ('test. dll ') # Note: Generally, test is used in linux. o file, you can also use the following method: # dll = ctypes. cdll. loadLibrary ('test. O ')
2.
import ctypesdll = ctypes.CDll( 'test.dll' )
I hope this article will help you with Python programming.