julia> using Cxx
julia> cxx""" #include <vector> """
true
julia> cxx""" std::vector<int> a = std::vector<int> (5,6); """
true
julia> icxx""" a[0]; """
(int &) 6
julia> b = icxx""" a; """
(class std::vector<int, class std::allocator<int> >) {
}
julia> b[0]
6
julia> b
(class std::vector<int, class std::allocator<int> >) {
}
The above code, when entered into a Julia terminal, shows that the vector data is present. However, I'd prefer to completely transfer it into a Julia array. What is the best method of doing this?
Note: Eventually a shared library will be returning a std::vector<int>
, so the question, more explicitly, is how best to convert std::vector<int>
into a standard Julia vector. (This is referring to the variable b
in the example code).
Thanks in advance.
EDIT: The reasoning for why there is a problem doesn't seem to be clear, so hopefully the following will help (it follows on directly from the above code)
julia> unsafe_wrap(Array, pointer(b), length(b))
ERROR: MethodError: objects of type Ptr{Int32} are not callable
julia> @cxx b;
ERROR: Could not find `b` in translation unit
julia> cxx" b; "
In file included from :1:
__cxxjl_17.cpp:1:2: error: C++ requires a type specifier for all declarations
b;
^
true
julia> icxx" b; "
ERROR: A failure occured while parsing the function body
julia> cxx" &b; "
In file included from :1:
__cxxjl_15.cpp:1:3: error: C++ requires a type specifier for all declarations
&b;
^
__cxxjl_15.cpp:1:3: error: declaration of reference variable 'b' requires an initializer
&b;
^
true
julia> icxx" &b; "
ERROR: A failure occured while parsing the function body
julia> @cxx &b;
LLVM ERROR: Program used external function 'b' which could not be resolved!
No matter how you try to pass the julia referenced variable, it cannot be parsed back into the c++ environment (and the last one broke julia completely). Nor can the same methods used to pass c++ references into julia be used. Attempting to grab the pointer of either b
, @b
, b[0]
or &b[0]
and parsing those work.
If copying the data is acceptable, you can call collect
on the C++ vector to copy it to a julia vector. If you want to avoid copying, you can get the address of the data with icxx"&a[0];"
and wrap that using unsafe_wrap
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With