Skip to content

Instantly share code, notes, and snippets.

@eddieantonio
Last active March 18, 2019 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddieantonio/a9b4d4e249f193a011e17307dcfcff55 to your computer and use it in GitHub Desktop.
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.
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