What Julia type maps to a C type containing nested structs?

question
ccall

#1

Suppose I have a C type like this:

struct foo {
   int x;
   char y;
};
struct bar {
   struct foo q;
   int y;
};

and I need to be able to modify bar.q.x in-place, or it is modified by a C function that I pass the struct’s address to.

What is the proper Julia type declaration?


#2
julia> struct Foo
           x::Int
           y::UInt8
       end

julia> struct Bar
           q::Foo
           y::Int
       end

julia> sizeof(Bar)
24

julia> map(x->fieldoffset(Bar,x), 1:nfields(Bar))
2-element Array{UInt64,1}:
 0x0000000000000000
 0x0000000000000010

The object may be stored in a Ref: mb = Ref(Bar(Foo(1,0x8), 42)), the top-level content of which is mutable; unfortunately, updating the nested contents doesn’t have a convenient syntax yet:

https://github.com/JuliaLang/julia/pull/21912

(I believe there is a macro or package around to make that easier in the meantime, but I can’t find it at the moment. Hopefully someone else will provide a link)


#3

The most generic way to do it is to make both immutable and use a Ref{bar}() as the mutable container. For now you can load fields without much problem. If you need to mutate field, you’ll need to do some pointer arithmetic manually now and https://github.com/JuliaLang/julia/pull/21912 will provide full support for it.