Search code examples
juliamethod-call

How to specify a relative library path in Julia ccall?


to ccall a custom made library, I need to write down the library full path on the system:

j = ccall((:add3, "[FULL_PATH]/libmylib.so"), Float32, (Float32,), 2)

I am trying to use instead a relative path with:

j = ccall((:add3, "$(pwd())/libmylib.so"), Float32, (Float32,), 2)

but, while "$(pwd())/libmylib.so" returns the right path for the library, ccall with pwd returns a TypeError: in ccall: first argument not a pointer or valid constant expression, expected Ptr, got Tuple{Symbol,String}.

So, how to ccall a library that is in the same folder than the Julia script/current working directory ?

I am puzzled, as according to this thread in Windows seems to work, even if the doc for ccall specify:

Note that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression.

For info, I'm in Ubuntu 18.04 and the library has been implemented with

mylib.c:

float add3 (float i){
 return i+3;
}

mylib.h:

#ifndef _MYLIB_H_
#define _MYLIB_H_

extern float get2 ();
extern float add3 (float i);

Compilation (gcc):

gcc -o mylib.o -c mylib.c
gcc -shared -o libmylib.so mylib.o -lm -fPIC

Solution

  • As far as I know this is the most used pattern:

    const mylib = joinpath(pwd(), "libmylib.so")
    j = ccall((:add3, mylib), Cfloat, (Cfloat,), 2)
    

    Note that pwd can be a bit more in "flux" than you want for a library path, it is probably better to relate it to the file, e.g.

    const mylib = joinpath(@__DIR__, "libmylib.so")
    

    where @__DIR__ expands to the directory of the file itself.