I’m using a C library that uses C structs as internal data storage. However, the library assumes that the user will instantiate these structs him/herself, and then call an initialization routine on them. For instance, in the library header:
So… how do I instantiate a mystruct from Julia? I know I could create a Julia struct mirror definition, but I’d rather not. That would require me to know something about the internal structure of the library data types. There doesn’t seem to be any easy way to instantiate a composite C variable type from within Julia.
The mutable struct MyStruct is owned by Julia and will be garbage collected, but the call to Libc.malloc is allocating your own (you the user) memory that you need to manage. Luckily, it’s easy in Julia to add the finalizer(x->Libc.free(x.ptr) call, which ensures that when the MyStruct object goes out of scope and is garbage collected, it will free the underlying malloc-ed memory.