Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load DLL using ctypes in Python?

Tags:

python

Please provide me a sample explaining how to load & call a functions in c++ dll using Python?

I found some articles saying we can use "ctypes" to load and call a function in DLL using Python. But i am not able to find a working sample?

It would be great if anyone provide me an sample of how to do it.

like image 864
Madras Avatar asked Nov 23 '09 07:11

Madras


1 Answers

Here is some actual code I used in a project to load a DLL, lookup a function and set up and call that 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 a terminal emulator package and it was a very simple one - it took four parameters and returned no value (some was actually returned via pointer parameters). The first parameter (1) is to indicate that we want to connect to the host.

The second parameter ("Z") is the session ID. This particular terminal emulator allowed short-name sessions of "A" through "Z".

The other two parameters were simply a length and another byte the use of which escapes me at the moment (I should have documented that code a little better).

The steps were to:

  • load the DLL.
  • Set up the prototype and parameters for a function.
  • Map that to a Python name (for ease of calling).
  • Create the necessary parameters.
  • Call the function.

The ctypes library has all the C data types (int, char, short, void* and so on), and can pass parameters either by value or reference. There's a tutorial located here.

like image 124
paxdiablo Avatar answered Oct 17 '22 21:10

paxdiablo