How can you modify global variables that are used in functions that are being called with ccall?

From the documentation, I got that it’s possible to retrieve pointers to global variables by using the cglobal function. However, I wasn’t able to figure out from that how I can set the value of a global variable that is being used in a function that I am calling via ccall, or how I can retrieve the resulting state of a global variable that was modified by said function. Is there a part of the documentation I missed, or some kind of more in-depth tutorial on how to use ccall available anywhere?

Since cglobal returns a pointer, you’d use unsafe_load/unsafe_store! to read/write values to/from that global variable.

@Sukera But will the modifications I make also be available in the subsequent ccall call? I assumed that ccall loads a fresh copy of the binary into memory, so any modifications made beforehand won’t be adopted

ccall doesn’t load libraries on its own. If the call succeeds, the library was already loaded. You’d use Libdl and dlopen to load a shared object (*.so) and the functions contained within. ccall does nothing more than locate that already located function, based on the function name you passed to it, and call it directly (i.e., push the arguments on the stack and jump to the code of the function).

Global variables in C are just some address in memory - they too have a name associated with them, and that’s what cglobal uses to return that address as a pointer.


You can ccall libraries you haven’t loaded beforehand just fine. But regardless ccall won’t close them after the call.