DEV Community

Cover image for Call DLL functions from Python
petercour
petercour

Posted on

2

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")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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:

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
advik2612 profile image
Advik

Omg TSYM

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay