First you need to create the C++ file that does what you want and expose it to Julia. Let’s call it sort.cpp
:
#include "jlcxx/jlcxx.hpp"
void sort_string(std::vector<std::string>& v)
{
std::sort(v.begin(), v.end());
}
JLCXX_MODULE define_julia_module(jlcxx::Module &mod)
{
// This exposes the function `sort_string` to the module.
mod.method("sort_string", &sort_string);
}
Now, you need to compile it. In my machine, I can run the following command:
clang++ \
--std=c++17 -shared -undefined dynamic_lookup \
-o libsort.dylib \
-I../../.julia/artifacts/c598c0cf1873e3cacf620287193aaf12bf5f8ace/include/ \
-I/Applications/Julia-1.7.app/Contents/Resources/julia/include/julia -L/Applications/Julia-1.7.app/Contents/Resources/julia/lib/Julia \
sort.cpp
In your case, you will need to change the paths. After that, I get the wrap library libsort.dylib
.
Now, we need to create a module in Julia that contains the wrapped functions. This is very simple and we will handle the type conversions between Julia arrays and std::vector
internally:
module Sort
using CxxWrap
@wrapmodule("libsort")
function sort(v::Vector{String})
# We need to convert the Julia vector into the
# `std::vector<std::string>`, which is already wrapped by CxxWrap.
svec = StdVector(CxxRef.(StdString.(v)))
# Call the function that will sort the vector using `std::sort`.
sort_string(svec)
# Now, just convert the sorted vector back to a Julia array.
return String[svec...]
end
function __init__()
@initcxx
end
end
Finally, you just need to include this module and the sort can be performed as follows:
julia> v = ["C", "X", "X", "W", "R", "A", "P"]
7-element Vector{String}:
"C"
"X"
"X"
"W"
"R"
"A"
"P"
julia> Sort.sort(v)
7-element Vector{String}:
"A"
"C"
"P"
"R"
"W"
"X"
"X"
Of course this example is the simplest way I found to perform what you described. There is probably 100 other alternatives much better and faster.