tags:

views:

6030

answers:

5

What is the easiest way to use a DLL from within Python?

Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python?

Native Python functionality is strongly preferred over using a 3rd party library.

+1  A: 

You might want to have a look at SWIG.

I don't know of any capabilities within the standard Python libraries to do this sort of thing. It looks like the ctypes library is new in version 2.5 and supports calling DLLs.

Greg Hewgill
+2  A: 

ctypes can be used to access dlls, here's a tutorial:

http://docs.python.org/library/ctypes.html#module-ctypes

monkut
A: 

ctypes will be the easiest thing to use but (mis)using it makes python subject to crashing. If you are trying to do something quickly, and you are careful, it's great. I would encourage you to check out boost python. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) C++ compiler from microsoft.

David Nehme
+16  A: 

I think ctypes is the way to go.

The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.

import ctypes

# Load DLL into memory.

hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")

# Set up prototype and parameters for the desired function call.
# HLLAPI

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 call ("HLLAPI(...)") to a Ptyhon name.

hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)

# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.

p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))

The ctypes stuff has all the C-type data types (int, char, short, void*, ...) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference).

paxdiablo
Yep, ctypes is great. Python has been blessed with a great built-in (since 2.5) way to access code in DLLs. ctypes is so easy to use that you have to think twice before writing real extensions, instead of just providing a pure Python module that uses ctypes to interface your DLL.
Eli Bendersky
A: 

simplest example of calling a dll have a look on this link here

i am using this.

atul