How to load DLL using ctypes in Python?

Please give me an example explaining how to load and call functions in a C ++ dll using Python?

I found several articles in which we can use "ctypes" to load and call a function in a DLL using Python. But I can not find a working sample?

It would be great if someone would provide me with a sample of how to do this.

+4
source share
1 answer

Here is some actual code that I used in the project to load the DLL, search for the function and configure and call this function.

import ctypes # Load DLL into memory. hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll") # Set up prototype and parameters for the desired function call # in the DLL, `HLLAPI()` (the high-level language API). This # particular function returns an `int` and takes four `void *` # arguments. hllApiProto = ctypes.WINFUNCTYPE ( ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0) # Actually map the DLL function to a Python name `hllApi`. hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams) # This is how you can actually call the DLL function. Set up the # variables to pass in, then call the Python name with them. p1 = ctypes.c_int (1) p2 = ctypes.c_char_p ("Z") p3 = ctypes.c_int (1) p4 = ctypes.c_int (0) hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4)) 

The function in this case was one in the package of the terminal emulator, and it was very simple - it took four parameters and did not return any value (some of them were actually returned using the pointer parameters). The first parameter (1) should indicate that we want to connect to the host.

The second parameter ("Z") is the session identifier. This particular terminal emulator allowed short sessions from "A" to "Z".

The other two parameters were just the length and the other byte, the use of which eludes me at the moment (I should have documented this code a little better).

The steps were as follows:

  • load the dll.
  • Set the prototype and parameters for the function.
  • Match this Python name (for easy calling).
  • Create the necessary parameters.
  • Call the function.

The ctypes library has all C data types ( int , char , short , void* , etc.) and can pass parameters either by value or by reference. There the tutorial is posted here .

+5
source

All Articles