Wrapping up C function in Julia

Hello! Another total noob here :slight_smile:

I’m wrapping up some C code in Julia and got stuck at one point.
There’s a function:

extern void  gsw_ct_first_derivatives (double sa, double pt, double *ct_sa, double *ct_pt);

How do I call it from Julia? I can’t find any appropriate ccal structure. Any input will be highly appreciated.

1 Like
# Instructions
# gcc -fPIC  -shared c2.c -o c2.so
#  where c2.c contains the following code:
# /* ======================================================================= */
# #include <math.h>

# void  gsw_ct_first_derivatives (double sa, double pt, double *ct_sa, double *ct_pt)
# {
#     *ct_sa = 2 * sa;
#     *ct_pt = 3 * pt;
# }
# /* ======================================================================= */

using Libdl

_C2LIB = dlopen("./c2.so")

sa = -13.0
pt = +2.0
ct_sa = Ref{Cdouble}(0.0)
ct_pt = Ref{Cdouble}(0.0)

ccall(dlsym(_C2LIB, :gsw_ct_first_derivatives), 
        Cvoid, 
        (Cdouble, Cdouble, Ptr{Cdouble}, Ptr{Cdouble}), 
        sa, pt, ct_sa, ct_pt)
@show sa, pt, ct_sa[], ct_pt[]

Produces output

julia> include("j2.jl")
(sa, pt, ct_sa[], ct_pt[]) = (-13.0, 2.0, -26.0, 6.0)
(-13.0, 2.0, -26.0, 6.0)
2 Likes

Great, thank you very much, Petr! Here’s my slightly modified code (works with Julia 1.0.1):

if Sys.islinux()
  const libgswteos = joinpath(@__DIR__, "libgswteos-10.so")
end
if Sys.iswindows()
  const libgswteos = joinpath(@__DIR__, "libgswteos-10.dll")
end

function gsw_ct_first_derivatives(sa, pt)
  ccall(("gsw_ct_first_derivatives",libgswteos),Cvoid,(Cdouble, Cdouble, Ptr{Cdouble}, Ptr{Cdouble}),sa, pt, ct_sa, ct_pt)
return ct_sa[], ct_pt[]
end

sa=34.
pt=20.
ct_sa = Ref{Cdouble}(0.0)
ct_pt = Ref{Cdouble}(0.0)

ct_sa[], ct_pt[] = gsw_ct_first_derivatives(sa, pt)
@show sa, pt, ct_sa[], ct_pt[]