2
votes

I want to write a Julia interface to a C library. For me it is necessary to translate a C struct to a Julia type. This is necessary because i want to make a call to a C function using ccall.

    struct my_struct {

        struct my_struct * child; 
        int a;

        struct A_st{
            int c; 
            int (*f1) (struct my_struct * eqn); 
            int (*f2) (struct my_struct * eqn); 
            int (*f3) (struct my_struct * eqn); 
        } A; 
    };

I know that Julia has a problem with circular defined types https://github.com/JuliaLang/julia/issues/269 "Simple" defined structs i have already mapped to a julia type but with this one i have problems.

1

1 Answers

3
votes

Declare the inner struct first, then use it as a member:

struct A_st
  c::Cint
  f1::Ptr{Void}
  f2::Ptr{Void}
  f3::Ptr{Void}
end

struct my_struct
  child::Ptr{my_struct}
  a::Cint
  A::A_st
end

Untested, but the Julia alignments look correct:

julia> map(i -> Int(fieldoffset(my_struct,i)), 1:3)
3-element Array{Int64,1}:
  0
  8
 16

julia> map(i -> Int(fieldoffset(A_st,i)), 1:4)
4-element Array{Int64,1}:
  0
  8
 16
 24

vs

clang -cc1 -fdump-record-layouts t.cpp

*** Dumping AST Record Layout
         0 | struct my_struct
         0 |   struct my_struct * child
         8 |   int a
        16 |   struct my_struct::A_st A
        16 |     int c
        24 |     int (*)(struct my_struct *) f1
        32 |     int (*)(struct my_struct *) f2
        40 |     int (*)(struct my_struct *) f3
           | [sizeof=48, dsize=48, align=8,
           |  nvsize=48, nvalign=8]