Last active
March 18, 2019 19:38
-
-
Save eddieantonio/a9b4d4e249f193a011e17307dcfcff55 to your computer and use it in GitHub Desktop.
Demo of compiling a small C dynamic library in a Python script and directly loading it with ctypes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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