DEV Community 👩‍💻👨‍💻

Cover image for Call DLL functions from Python
petercour
petercour

Posted on

Call DLL functions from Python

Do you hav experience with C programming?

You can call C functions from Python, with ctypes. What is ctypes?

ctypes is a foreign function library for Python. It provides C compatible data types, and allowscalling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

This how to do it in Python 2.x (if you still have that):

#!/usr/bin/python
from ctypes import *

libc = cdll.LoadLibrary("/lib/x86_64-linux-gnu/libc.so.6")
printf = libc.printf
printf("hello world\n")

For Python 3.x programs (yes the difference is one character)

#!/usr/bin/python3
from ctypes import *

libc = cdll.LoadLibrary("/lib/x86_64-linux-gnu/libc.so.6")
printf = libc.printf
printf(b"hello world\n")

Make sure the path to your shared library (libc.so.6) is right.

Chances are it's on another location. On Windows or Mac its different path and name. Otherwise it's very basic, and this should work for any C library.

Related links:

Top comments (1)

Collapse
 
advik2612 profile image
Advik

Omg TSYM

Build Anything...


Use any Linode offering to create something for the DEV x Linode Hackathon 2022. A variety of prizes are up for grabs, inculding $1,000 USD. 👀

Join the Hackathon <-