This is a short note how to get started of wrapping C++ libraries to Julia. Two approaches exists: the use of Cxx.jl or use of CxxWrap.jl. This first blog post contains a minimum working example, how to create a shared library and wrap it to Julia.
cd(tempdir())
pwd()
Normally it makes sense to define wrapper in a separate file, but like said, let's keep things as simple as possible first.
hello_content = """
#include <string>
std::string greet()
{
return "hello, world";
}
// Wrapper start
#include "jlcxx/jlcxx.hpp"
JLCXX_MODULE define_julia_module(jlcxx::Module& mod)
{
mod.method("greet", &greet);
}
"""
open("hello.cpp", "w") do fid write(fid, hello_content) end
Header files for Julia and CxxWrap is needed to compile code to object file.
using CxxWrap
cxxwrap_include_path = abspath(dirname(pathof(CxxWrap)), "..", "deps", "usr", "include")
julia_include_path = abspath(Sys.BINDIR, Base.INCLUDEDIR, "julia")
cxxwrap_include_path, julia_include_path
run(`g++ -c -I$cxxwrap_include_path -I$julia_include_path -fPIC hello.cpp`)
Then we can build the shared library:
cxxwrap_libfile = CxxWrap.libcxxwrap_julia
cxxwrap_libpath = dirname(cxxwrap_libfile)
julia_libpath = abspath(julia_include_path, "..", "..", "lib")
cxxwrap_libfile, cxxwrap_libpath, julia_libpath
run(`g++ hello.o -shared -o libhello.so -L/opt/julia/lib -Wl,-rpath,$cxxwrap_libpath: $cxxwrap_libfile -ljulia`)
;ls -l /tmp/libhello.so
There it is! The last thing to do is to write a short Julia code which utilizes a shared library:
module CppHello
using CxxWrap
@wrapmodule(joinpath(".","libhello"))
function __init__()
@initcxx
end
end
CppHello.greet()
Of course, several things can be done more efficiently. For example, usually wrapper should be written to separate file and the whole process of compiling a shared library should be done using Makefile. We get into these improvements in further blog posts.