How can I use a DLL file from Python?

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.

Asked by: Clark791 | Posted: 28-01-2022

Answer 1

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.

import ctypes

# Load DLL into memory.

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

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

hllApiProto = ctypes.WINFUNCTYPE (
    ctypes.c_int,      # Return type.
    ctypes.c_void_p,   # Parameters 1 ...
    ctypes.c_void_p)   # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),

# Actually map the call ("HLLAPI(...)") to a Python 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 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 int so, while I specify int as 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:

int hllApi (void *p1, void *p2, void *p3, void *p4)

This makes for a single, simple ctypes function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate ctypes function set up per library function.

The return value from WINFUNCTYPE is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in hllApiParams has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the ctypes doco for details

Once you have the prototype and parameter information, you can create a Python "callable" hllApi with which to call the function. You simply create the needed variable (p1 through p4 in my case) and call the function with them.

Answered by: Dainton217 | Posted: 01-03-2022

Answer 2

This page has a very simple example of calling functions from a DLL file.

Paraphrasing the details here for completeness:

It's very easy to call a DLL function in Python. I have a self-made DLL file with two functions: add and sub which take two arguments.

add(a, b) returns addition of two numbers
sub(a, b) returns substraction of two numbers

The name of the DLL file will be "demo.dll"


from ctypes import*
# give location of dll
mydll = cdll.LoadLibrary("C:\\demo.dll")
result1= mydll.add(10,1)
result2= mydll.sub(10,1)
print "Addition value:"+result1
print "Substraction:"+result2


Addition value:11

Answered by: Grace446 | Posted: 01-03-2022

Answer 3

Building a DLL and linking it under Python using ctypes

I present a fully worked example on how building a shared library and using it under Python by means of ctypes. I consider the Windows case and deal with DLLs. Two steps are needed:

  1. Build the DLL using Visual Studio's compiler either from the command line or from the IDE;
  2. Link the DLL under Python using ctypes.

The shared library

The shared library I consider is the following and is contained in the testDLL.cpp file. The only function testDLL just receives an int and prints it.

#include <stdio.h>
extern "C" {
void testDLL(const int i) {
    printf("%d\n", i);
} // extern "C"

Building the DLL from the command line

To build a DLL with Visual Studio from the command line run

"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\vsdevcmd"

to set the include path and then run

cl.exe /D_USRDLL /D_WINDLL testDLL.cpp /MT /link /DLL /OUT:testDLL.dll

to build the DLL.

Building the DLL from the IDE

Alternatively, the DLL can be build using Visual Studio as follows:

  1. File -> New -> Project;
  2. Installed -> Templates -> Visual C++ -> Windows -> Win32 -> Win32Project;
  3. Next;
  4. Application type -> DLL;
  5. Additional options -> Empty project (select);
  6. Additional options -> Precompiled header (unselect);
  7. Project -> Properties -> Configuration Manager -> Active solution platform: x64;
  8. Project -> Properties -> Configuration Manager -> Active solution configuration: Release.

Linking the DLL under Python

Under Python, do the following

import os
import sys
from ctypes import *

lib = cdll.LoadLibrary('testDLL.dll')


Answered by: Arnold900 | Posted: 01-03-2022

Answer 4

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

Answered by: Dexter187 | Posted: 01-03-2022

Answer 5

Maybe with Dispatch:

from win32com.client import Dispatch

zk = Dispatch("zkemkeeper.ZKEM") 

Where zkemkeeper is a registered DLL file on the system... After that, you can access functions just by calling them:

zk.Connect_Net(IP_address, port)

Answered by: Aida610 | Posted: 01-03-2022

Answer 6

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.

Answered by: Max168 | Posted: 01-03-2022

Answer 7

If the DLL is of type COM library, then you can use pythonnet.

pip install pythonnet

Then in your python code, try the following

import clr

# import the namespace and class

from Namespace import Class

# create an object of the class

obj = Class()

# access functions return type using object

value = obj.Function(<arguments>)

then instantiate an object as per the class in the DLL, and access the methods within it.

Answered by: Lily634 | Posted: 01-03-2022

Similar questions

Python - When to use file vs open

What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)

python name a file same as a lib

i have the following script import getopt, sys opts, args = getopt.getopt(sys.argv[1:], "h:s") for key,value in opts: print key, "=&gt;", value if i name this and run it doesn't work as it tries to import itself is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? Solution based ...

Python FTP Most Recent File

This question already has answers here:

XML file using Python

I have made a XML file using python. How can I retrieve an element from it? Will you help me with the code? Also I need to have my output (i.e. element of each attribute come in separate lines in that particular XML file).

file - What does 'wb' mean in this code, using Python?

Code: file('pinax/media/a.jpg', 'wb')

run python file

i dont have any experience in python programming but I get to run python file is there any one to help me pls here is the file content &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; #!/usr/local/bin/python """ Based on: According to that project, this file is licensed under the LGPL """ try: from pyparsing import (ParserElement, Liter...

python - How to get self file name

This question already has answers here:

how add new line in CSV file using python

I have a csv file that contains time (hh:mm:ss) and date (mm/dd/yyyy) fields, and sixteen more fields. Generally the time field display time every 30'', but sometime the separation might be more (minutes or even hours). For instance: 1/27/2011 12:10:00 1/27/2011 12:10:30 1/27/2011 12:11:00 1/27/2011 12:15:00 I need to add new lines (as many as the gap between them) every...

python - How do I get the file / key size in boto S3?

There must be an easy way to get the file size (key size) without pulling over a whole file. I can see it in the Properties of the AWS S3 browser. And I think I can get it off the "Content-length" header of a "HEAD" request. But I'm not connecting the dots about how to do this with boto. Extra kudos if you post a link to some more comprehensive examples than are in the

pdf file with python

How can search a word or a line in a pdf file? Is there an existing module to do that by being concise? Thank you in advance,

python - What's the best Django search app?

python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.

python - What is the best way to copy a list?

This question already has answers here:

python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?

python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...

python - How do I turn an RSS feed back into RSS?

According to the feedparser documentation, I can turn an RSS feed into a parsed object like this: import feedparser d = feedparser.parse('') but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XM...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python