Hi Andraeas,

The documentation has a paragraph about this:

http://docs.julialang.org/en/release-0.3/manual/calling-c-and-fortran-code/ 
:

"Currently, it is not possible to reliably pass structs and other 
non-primitive types by *value* from Julia to/from C libraries. However, 
*pointers* to structs can be passed. The simplest case is that of C 
functions that generate and use *opaque* pointers to struct types, which 
can be passed to/from Julia as Ptr{Void} (or any other Ptr type). Memory 
allocation and deallocation of such objects must be handled by calls to the 
appropriate cleanup routines in the libraries being used, just like in any 
C program. A more complicated approach is to declare a composite type in 
Julia that mirrors a C struct, which allows the structure fields to be 
directly accessed in Julia. Given a Julia variable x of that type, a 
pointer can be passed as &x to a C function expecting a pointer to the 
corresponding struct. If the Julia type T is immutable, then a Julia 
Array{T} is stored in memory identically to a C array of the corresponding 
struct, and can be passed to a C program expecting such an array pointer."

I have never tried using the immutable approach to mirror a C structure, 
but it looks interesting.  Instead, I use the Ptr{Void} method.  So, in 
your C code you might have a couple of methods for building your type and 
setting a and b in your structure,

void* builder() { return (void*) malloc(sizeof(struct mytype)); }
void setter(struct mytype *t, int a, int b) { t.a=a ; t.b=b; }

Then in your Julia code, you would write something like,
 
t = ccall((:builder, "mylib"), Ptr{Void}, ())
ccall((:setter, "mylib"), Void, (Ptr{Void}, Int32,Int32), t, 1, 2)

Hope it helps.

Sam

On Thursday, January 8, 2015 3:29:21 AM UTC-6, Andreas Lobinger wrote:
>
> Hello colleagues,
>
> i thought i understood the ccall interface but now i ran into a problem 
> (segmentation fault) and i cannot really track down, where actually the 
> problem occures.
> I want/need to pass a pointer to structure (c style) to a library and the 
> function in the library writes entries in the structure.
>
> (the following i write from memory, i do not have the code on this 
> computer...)
>
> type mytype
>     a::Int32
>     b::Int32
> end
>
> t = mytype(0,0)
>
> ccall(:flip, Void, (mytype,), t)
>
>
> 1) is there somewhere code you would recommend to read?
> 2) how can i use code_lowered or code_llvm to actually see the details. 
> The above example is included in a module and it looks like the code is 
> compiled at 'using' so code_llvm e.g. only shows the call to the compiled 
> function, but not the inside.
> 3) other documentation (blog, FR) etc?
>
> Wishing a happy day,
>       Andreas
>

Reply via email to