C Interface -- How to store an element in a C array

#1

Hello,

I have an an old bit of code, written by someone else, that I need to convert to Julia 1.0. I’ve begun the conversion, but I’m stuck:

struct ttvfast_RV_entry
  time::Cdouble
  RV::Cdouble
end
...
nrvs = 100
rv_workspace = Libc.calloc(nrvs,sizeof(ttvfast_RV_entry))

# ... rv_times is a regular Julia Array{Float,1}.
for i in 1:nrvs
    pointer_to_array(
        convert(Ptr{ttvfast_RV_entry},rv_workspace),
        nrvs
    )[i] = ttvfast_RV_entry(rv_times[i],0.0)
end

The function pointer_to_array no longer exists in Julia. I’m not 100% sure of what it did, but clearly the goal is to populate the C array rv_workspace.

I’ve been reading through the documentation, but I can’t figure out how to insert a value into a C array; especially for a non-primitive type. I would welcome any suggestions. I’m sure there’s a straight forward way to do this.

Thanks!

0 Likes

#2

Just as a general piece of advice, you will have a much easier time upgrading code if you take the time to go through every Julia version, rather than skipping all the way to 1.0. If the code was written for Julia v0.5, then I would suggest:

  • Test with 0.5
  • Test with 0.6 and fix any deprecation warnings
  • Test with 0.7 and fix any deprecation warnings
  • Test with 1.0

That way you’ll get precise deprecation messages that tell you how to change the code, rather than just having to guess what functions that no longer exist used to do.

See also PSA: use Julia 0.7 if you are upgrading

0 Likes

#3

Is this just a simple example:

rv_workspace = Libc.calloc(nrvs,sizeof(ttvfast_RV_entry))
...
    pointer_to_array(
        convert(Ptr{ttvfast_RV_entry},rv_workspace),
        nrvs
    )

Or are you actually allocating the memory in Julia?
If so, just create it as a regular Julia array in the first place, and call pointer on it if you need a pointer (although ccall does that automatically).

If you’re allocating memory from the C side, you can use unsafe_wrap.

0 Likes

#4

@Elrod That is the actual code. It’s not mine but I’m sure they’d accept a PR from me. Yes, it’s actually allocating the memory in Julia. Thanks for the advice! I’ll try to change it to a regular Julia array and call pointer.

0 Likes

#5

Use unsafe_store! instead on the pointer. (Feel free to comment for any usage questions after reading the docs for it.)

0 Likes