C-Compatible Julia Function

I compiled your C demo as follows:

gcc -shared -fPIC test.c -o test.so

You can invoke your C function via

using Libdl
lib_handle = Libdl.dlopen(joinpath(pwd(), "test.so"))
test_function_handle = Libdl.dlsym(lib_handle, :test)
myFun_function_handle = Libdl.dlsym(lib_handle, :myFun)

function c_test(a, b, c, f)
    return ccall(test_function_handle , Cvoid, (Cdouble, Cdouble, Ptr{Cdouble}, Ptr{Cvoid}), a, b, c, f)
end

function myFun(a::Cdouble, b::Cdouble, c::Ptr{Cdouble})
    unsafe_store!(c, a * b)
    return nothing
end

function main()
 a = 3.0
 b = 4.0
 c = Ref{Cdouble}(0.0)
 c_myFun = @cfunction(myFun, Cvoid, (Cdouble, Cdouble, Ptr{Cdouble}))
 c_test(a, b, c, c_myFun)

 a = 5.0
 c_test(a, b, c, myFun_function_handle)
end

When I invoke this I get the following:

julia> main()
c before f = 0.000000 
c after f = 12.000000 
c before f = 12.000000 
c after f = 20.000000 
8 Likes