Demo of compiling a small C dynamic library in a Python script and directly loading it with ctypes.
import ctypes | |
import tempfile | |
import distutils.ccompiler | |
from pathlib import Path | |
from random import randint | |
SOURCE_CODE = f""" | |
int roll(void) {{ | |
return {randint(1, 6)}; | |
}} | |
""" | |
def compile_link_and_load(source_code): | |
with tempfile.TemporaryDirectory() as tempdir_name: | |
tempdir = Path(tempdir_name) | |
source_file = tempdir / 'fairdice.c' | |
source_file.write_text(source_code, encoding='UTF-8') | |
cc = distutils.ccompiler.new_compiler() | |
object_files = cc.compile([str(source_file)], tempdir_name, extra_preargs=['-fPIC']) | |
cc.link_shared_lib(object_files, tempdir / 'fairdice') | |
return ctypes.CDLL(tempdir / 'libfairdice.so') | |
def main(): | |
libfairdice = compile_link_and_load(SOURCE_CODE) | |
print(libfairdice.roll()) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment