Create a C struct in Julia without knowing the internals?

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:

typedef struct{
    mydata data;
} mystruct;
MY_DEF void mystruct_initialize(mystruct* sph);

and the user is expected to do the following:

mystruct foo;

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.

If you at least know the size of mystruct, you could do something like:

mutable struct MyStruct
    function MyStruct()
        foo = new(Libc.malloc(SIZEOF_mystruct))
        finalizer(x->, foo)
        ccall(:mystruct_initialize, Cvoid, (Ptr{Void},), foo.ptr)
        return foo

It might not be quite syntactically correct, but hopefully that gives you the idea at least.

Is the resulting allocated memory owned by Julia (and hence garbage collected) or by C?

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-> call, which ensures that when the MyStruct object goes out of scope and is garbage collected, it will free the underlying malloc-ed memory.