unsafe_pointer_to_objref expects a reference to a Julia object (allocated
by Julia), whereas you've passed a reference to memory allocated by C.
Julia types are layout-compatible with C, but it still matters who
allocated them when doing the translation.

unsafe_load should work for you.

On Mon Feb 23 2015 at 8:57:50 AM Juhani Kataja <[email protected]> wrote:

> Hello!
>
> I started experimenting with Julia<->C interface and found out that it
> seems to be hard to pass a struct defined in C to a callback function
> defined in Julia as follows:
>
> type ab_struct
>   a::Cint
>   b::Cdouble
> end
>
> function const_ab_struct(a_::Cint, b_::Cdouble, c_::Ptr{ab_struct})
>   c_ref = unsafe_pointer_to_objref(c_)
>   c_ref.a = a_
>   c_ref.b = b_
>   return 0
>   retval::Cint
> end
>
> const c_const_ab_struct = cfunction(const_ab_struct, Cint, (Cint, Cdouble,
> Ptr{ab_struct}))
> ccall( (:testme_ab_callback, "my_lib"), Void, (Ptr{Void},),
> c_const_ab_struct)
>
> In "my_lib" dynamic library I have
> typedef struct {
>   int a;
>   double b;
> } ab_struct;
>
> void testme_ab_callback(int (*fun)(int, double, ab_struct*))
> {
>   ab_struct foo;
>   fun(1,0.5,&foo);
>   printf("%i, %f\n", foo.a, foo.b);
> }
>
> This will yield segfault (seemingly) from c_ref.a=a_ (I'm using osx 10.10
> and julia version 0.3.5 installed from .dmg)
>
> Am I doing something wrong (which is a more probable than..)? Is this kind
> of struct-callback construct possible to implement (cleanly)?
>
> Thanks,
> Juhani
>

Reply via email to