What is the easiest way to use a DLL file 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 third-party library.
For ease of use, 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.
The
ctypesstuff has all the C-type data types (int,char,short,void*, and so on) 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).In terms of the specific example shown above, IBM’s EHLLAPI is a fairly consistent interface.
All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an
intso, while I specifyintas the return type, I can safely ignore it) as per IBM’s documentation here. In other words, the C variant of the function would be:This makes for a single, simple
ctypesfunction able to do anything the EHLLAPI library provides, but it’s likely that other libraries will need a separatectypesfunction set up per library function.The return value from
WINFUNCTYPEis a function prototype but you still have to set up more parameter information (over and above the types). Each tuple inhllApiParamshas a parameter ‘direction’ (1 = input, 2 = output and so on), a parameter name and a default value – see thectypesdoco for detailsOnce you have the prototype and parameter information, you can create a Python ‘callable’
hllApiwith which to call the function. You simply create the needed variable (p1throughp4in my case) and call the function with them.