brenhinkeller / StaticTools.jl

Enabling StaticCompiler.jl-based compilation of (some) Julia code to standalone native binaries by avoiding GC allocations and llvmcall-ing all the things!
MIT License
167 stars 12 forks source link

Calling StaticTools.dlopen vs StaticCompiler.dlopen #51

Closed mdmaas closed 4 months ago

mdmaas commented 1 year ago

Hi,

I'm trying to compile code which calls external shared libraries (like a static version of ccall, see also here)

### Let's define a C function and compile it
using Libdl
C_code= """
       double mean(double a, double b) {
         return ( a + b ) / 2;
       }
       """
Clib = "clib"
open(`gcc -fPIC -O3 -xc -shared -o $(Clib * "." * Libdl.dlext) -`, "w") do f
    print(f, C_code)
end

# Now the julia code

using StaticTools, StaticCompiler

function test()
    lib_path = c"/home/martin/Desktop/extras/static_compiler_test/static_ccall/clib.so"
    func_name = c"mean"

    lib = StaticCompiler.dlopen(lib_path)
    mean = StaticCompiler.dlsym(lib, func_name)
    a = 1.0
    b = 2.0
    c = @ptrcall mean(a::Float64, b::Float64) :: Float64
    printf(c"Result is %f:\n", c)

    return 0
end

test()

Of course, I would like to compile it, but if I replace StaticCompiler.dlopen with StaticTools.dlopen (which would compile) it doesn't work (I got a segfault):

[5684] signal (11.1): Segmentation fault
in expression starting at /home/martin/Desktop/extras/static_compiler_test/static_ccall/test_mean.jl:53
unknown function (ip: (nil))
Allocations: 1333178 (Pool: 1332179; Big: 999); GC: 2
Segmentation fault

Do you think there could be a problem with StaticTools.dlopen and/or with @ptrcall?

mdmaas commented 1 year ago

Oh, I think there is no problem with @ptrcall, it's only that I'm being able to use StaticTools.dlopen properly, as it returns a null pointer...