I’m aware of existing … packages for wrapping C++, this is really more of a learning exercise for me (and I’m trying to learn enough to read what is in the existing pacages). I knew that it was possible to get C++ to give me a pointer to the contiguous memory of the std::vector
contents, so I figured that I would hand it over to Julia like this:
#include <vector>
#include <julia.h>
#include <iostream>
JULIA_DEFINE_FAST_TLS
int main(int argc, char *argv[]) {
std::vector<int> stuff = {1, 2, 3, 4}; // ordinarily, I'd use `auto` but wanted to be explicit
auto contents = stuff.data();
std::cout << "stuff.data(): " << stuff.data() << "\n";
std::cout << "stuff.data()[0]: " << contents[0] << "\n"; // prints 1
std::cout << "stuff.data()[1]: " << contents[1] << "\n"; // prints 2
std::cout << "stuff.data()[2]: " << contents[2] << "\n"; // prints 3
std::cout << "stuff.data()[3]: " << contents[3] << "\n"; // prints 4
std::cout << "stuff.size(): " << stuff.size() << std::endl;
jl_init();
jl_value_t *array_type = jl_apply_array_type((jl_value_t *)jl_int64_type, 1);
jl_array_t *julia_stuff = jl_ptr_to_array_1d(array_type, contents, stuff.size(), 0);
// Have Julia print your vector.
jl_function_t *prnt = jl_get_function(jl_base_module, "println");
jl_call1(prnt, (jl_value_t *)julia_stuff);
jl_atexit_hook(0);
return EXIT_SUCCESS;
}
Built it with:
function build_cpp_thing {
source_file=$1
basename="${source_file%%.*}"
g++ -I$JULIA_DIR/usr/include/julia \
-L$JULIA_DIR/usr/lib \
-Wl,-rpath,$JULIA_DIR/usr/lib \
-g \
$source_file -ljulia -o $basename
}
however, I seem to get garbage out of the print line:
stuff.data(): 0x563fc0cd4b20
stuff.data()[0]: 1
stuff.data()[1]: 2
stuff.data()[2]: 3
stuff.data()[3]: 4
stuff.size(): 4
[8589934593, 17179869187, 0, 1041]
??