Skip to content

Instantly share code, notes, and snippets.

@xealits
Last active January 24, 2026 15:48
Show Gist options
  • Select an option

  • Save xealits/9365b19882ba411711e39e7d723074e4 to your computer and use it in GitHub Desktop.

Select an option

Save xealits/9365b19882ba411711e39e7d723074e4 to your computer and use it in GitHub Desktop.
C hotreload/figwheel in Python
#!/usr/bin/env python
import ctypes
from ctypes import cdll
cur_x = 10
libpath = "./some_lib.so"
lib = cdll.LoadLibrary(libpath)
print(f"loaded {lib}")
# https://stackoverflow.com/a/62021495/1420489
def ctypesCloseLibrary(lib):
dlclose_func = ctypes.CDLL(None).dlclose
dlclose_func.argtypes = [ctypes.c_void_p]
dlclose_func.restype = ctypes.c_int
dlclose_func(lib._handle)
def reloadLibrary(lib):
name = lib._name
ctypesCloseLibrary(lib)
return cdll.LoadLibrary(name)
while True:
inp = input("> ")
inp = inp.strip().upper()
if inp == "X":
x = lib.foo(cur_x)
print(x)
elif inp == "L":
lib = reloadLibrary(lib)
print(f"reloaded {lib}")
else:
print(f"unknown input {inp}")
@xealits
Copy link
Author

xealits commented Oct 2, 2025

just to write it down:

# Makefile
%.o: %.c
	gcc -c -fPIC -g $< -o $@

%.so: %.o
	gcc $< -shared -o $@

Or:

%.o: %.cpp
	g++ -std=c++23 -c -fPIC -g $< -o $@

%.so: %.o
	g++ -std=c++23 $< -shared -o $@

@xealits
Copy link
Author

xealits commented Jan 24, 2026

Related links: c++filt <symbol>, use nm for symbols and nm -C to demangle, set arguments and return types of the function in ctypes.

func = libdll.func
func.argtypes = (ctypes.c_uint32,
                 ctypes.c_float,
                 ctypes.c_longlong * 8,
                 ctypes.c_void_p,
                 ctypes.c_char_p,
                 ctypes.POINTER(cts.c_ubyte))

func.restype = ctypes.c_double

In a multi-process case, when Python forks processes that fork others that eventually call Cpp code, make GDB follow child processes with set follow-fork-mode child. Keep set detach-on-fork on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment