Function Binding at Runtime

51 views
Skip to first unread message

Serhat Sevki Dincer

unread,
Dec 17, 2025, 11:41:44 PM (16 hours ago) Dec 17
to golang-nuts
Hi,

I was looking at purego dynamic loading library (without cgo) and loved the idea.
It seems to be working quite well across many OS/ARCH combinations.
You first Dlopen a library, then RegisterLibFunc functions from it.

In sdl3 binding library, it is effectively used like this:

var sdlInit func(InitFlags) bool
func init() {
    libSDL, _ := purego.Dlopen(libraryFileName, purego.RTLD_LAZY)
    purego.RegisterLibFunc(&sdlInit, libSDL, "SDL_Init")
}
func Init(flags InitFlags) bool {
    return sdlInit(flags)
}

So
sdlInit is an unexported, mutable variable set at runtime (application start)
Init is bound at link-time, exported and immutable (let's ignore function inlining)
- they have the exact same signature, you can do: sdlInit = Init

Go already allows implementing a function outside the language (in Assembly) like
func Init(flags InitFlags) bool
// implementation in Assembly

But this is still bound at link-time. What I am wondering is the possibility to have just the following and get rid of writable variables like sdlInit:
func Init(InitFlags) bool
func init() {
    libSDL, _ := purego.Dlopen(libraryFileName, purego.RTLD_LAZY)
    purego.RegisterLibFunc(&Init, libSDL, "SDL_Init")
}

So this is like filling a function pointer table at runtime (application startup). This would be doable only from inside init(). What do you think?

Regards..

Brian Candler

unread,
4:13 AM (11 hours ago) 4:13 AM
to golang-nuts
> So this is like filling a function pointer table at runtime (application startup)

Why not simply:

var Init func(InitFlags) bool
func init() {
    libSDL, _ := purego.Dlopen(libraryFileName, purego.RTLD_LAZY)
    purego.RegisterLibFunc(&Init, libSDL, "SDL_Init")
}

e.g. https://go.dev/play/p/X6LGwo9cAkH

Brian Candler

unread,
4:22 AM (11 hours ago) 4:22 AM
to golang-nuts
I guess the downside is that consumers can also alter the value of Init.

You want something like a "const" which can be initialized at runtime, which doesn't exist in Go. The solution generally is to make a public accessor function to a hidden variable, and that is the "var sdlInit" in your original code.
Reply all
Reply to author
Forward
0 new messages