diff --git a/ffi/internal/ffi_library.nim b/ffi/internal/ffi_library.nim index e0e00e8..e43ec87 100644 --- a/ffi/internal/ffi_library.nim +++ b/ffi/internal/ffi_library.nim @@ -147,6 +147,12 @@ macro declareLibrary*(libraryName: static[string], libType: untyped): untyped = let addName = libraryName & "_add_event_listener" let addErr = "error: invalid context in " & addName let addBody = quote: + # Runs on the foreign caller thread, which may not be the one that ran a + # prior entry point: initialize this thread's GC before any Nim allocation + # ($eventName / the registry Table+seq), else the per-thread allocator + # region is uninitialized and faults. + when declared(initializeLibrary): + initializeLibrary() var ret: uint64 = 0 if isNil(ctx): echo `addErr` @@ -181,6 +187,8 @@ macro declareLibrary*(libraryName: static[string], libType: untyped): untyped = let removeName = libraryName & "_remove_event_listener" let removeErr = "error: invalid context in " & removeName let removeBody = quote: + when declared(initializeLibrary): + initializeLibrary() var ret: cint = 1 if isNil(ctx): echo `removeErr`