On Thu, Nov 12, 2015 at 11:50 AM, Chris Cheetham
<chipandrud...@gmail.com> wrote:
> Hi Yichao Yu,
>
> Thank you for the excellent reply. I have updated to 4.0 and followed your
> advice below which has resolved all of my issues.
>
> Kind regards,
> Chris
>
> Next problem:
> How are Dictionaries represtented
>

Surprise, Dict is implemented in Julia and not in C [1]. You can
access it's members just like any types in julia but I think this is
regarded as an internal implementation detail that you shouldn't rely
on.

I'm not sure how people usually do it for embedding but my guess is
that you can access a Dict by constructing an API function in julia
and pass (the cfunction() of) it to c via ccall/cglobal. (This is how
pypy embedding works AFAIK).

Something like (totally not tested!!!!!!)

```
function c_dict_getindex(pdict::Ptr{Void}, pkey::Ptr{Void})
    dict = unsafe_pointer_to_objref(pdict)::Dict
    key = unsafe_pointer_to_objref(pkey)
    val = dict[key]
    pointer_from_objref(val)
end

ccall(:register_my_dict_access_api, Void, (Ptr{Void},),
cfunction(c_dict_getindex, Ptr{Void}, Tuple{Ptr{Void},Ptr{Void}}))
```

Or if you have more specific knowedge about the types
```
function c_dict_getindex_int(pdict::Ptr{Void}, key::Int) # the ::Int
is not necessary and is only for clarity
    dict = unsafe_pointer_to_objref(pdict)::Dict
    val = dict[key]
    pointer_from_objref(val)
end

ccall(:register_my_dict_access_api_for_int_dict, Void, (Ptr{Void},),
cfunction(c_dict_getindex_int, Ptr{Void}, Tuple{Ptr{Void},Int}))
```

(Note that Int in julia is pointer size, use `Cint` julia type for `int` in C)

[1] 
https://github.com/JuliaLang/julia/blob/53931509770e1571cc8218325629146efa9b2514/base/dict.jl#L380

>
> On Friday, November 6, 2015 at 4:34:37 PM UTC, Chris Cheetham wrote:
>>
>> Hi there,
>>
>> I am currently playing with Julia calls from C. I have made some good
>> progress insofar as calling Julia functions, boxing/unboxing etc. What I am
>> particularly interested in however is being able to return a type which
>> consists of a number of Float64s and being able to get/set their values on
>> the C side.
>>
>> For example
>>
>> type Example
>>         a::Float64
>> b::Float64
>> c::Float64
>> end
>>
>>
>> Unboxing returns a copy of a value, so no means to then set it and
>> jl_get_nth_field seems to also do the same.
>>
>>
>> I am able to get a reference to the value using pointer arithmetic by
>> getting jl_value_t + 1. I'm assuming the raw jl_value_t pointer is the type
>> pointer? and offsetting by 1 is the pointer to the value?
>>
>> Accessing elements in the type seems possible by further offsetting the
>> pointer  jl_value_t + 1 + elementIndex. My question is, is this a safe
>> assumption to make? Or is there a better way to be doing this that I haven't
>> spotted yet?
>>
>> Thanks,
>> Chris
>>
>>
>>
>

Reply via email to