How do I call a C function from a library installed with `apt install` using ctypes?

94 views Asked by At

I am trying to call ulc_width_linebreaks from unilbrk from GNU's libunistring (a C function) on my Python strings using the ctypes module. libunistring is available on Ubuntu, and I've installed it with sudo apt install libunistring2 libunistring-dev. I opened a new terminal window and tried to import the library from Python. I tried the following but all returned None:

ctypes.util.find_library("libunistring")
ctypes.util.find_library("libunistring2")
ctypes.util.find_library("unilbrk")
ctypes.util.find_library("unilbrk.h")
1

There are 1 answers

0
AudioBubble On

You need to find the install location of the library, which you can do with

$ dpkg -L libunistring2
/.
/usr
/usr/lib
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/libunistring.so.2.1.0
/usr/share
/usr/share/doc
/usr/share/doc/libunistring2
/usr/share/doc/libunistring2/changelog.Debian.gz
/usr/share/doc/libunistring2/copyright
/usr/lib/x86_64-linux-gnu/libunistring.so.2

and then load it and call it like this

import ctypes
from pathlib import Path

libunistring_path = Path("/usr/lib/x86_64-linux-gnu/libunistring.so")
libunistring = ctypes.CDLL(libunistring_path)
libunistring.ulc_width_linebreaks.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]

libunistring.ulc_width_linebreaks("your args here")