将Cxx Vector转换为Julia Vector

use*_*504 3 c++ vector type-conversion julia

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> >) {
}
Run Code Online (Sandbox Code Playgroud)

当输入Julia终端时,上述代码显示存在矢量数据.但是,我更愿意将其完全转移到Julia数组中.这样做的最佳方法是什么?

注意:最终共享库将返回a std::vector<int>,因此更明确的问题是如何最好地转换std::vector<int>为标准Julia向量.(这是指示b例代码中的变量).

提前致谢.

编辑:为什么有问题的原因似乎并不清楚,所以希望以下将有所帮助(它直接来自上面的代码)

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!
Run Code Online (Sandbox Code Playgroud)

无论你如何尝试传递julia引用变量,它都无法解析回c ++环境(最后一个完全破坏了julia).也不能使用用于将c ++引用传递到julia的相同方法.试图抓住任何的指针b,@b,b[0]&b[0]和解析这些工作.

Jef*_*son 6

如果可以接受复制数据,则可以调用collectC++向量将其复制到julia向量.如果要避免复制,可以使用icxx"&a[0];"并获取数据的地址unsafe_wrap.

  • 你试过`unsafe_wrap(Array,icxx"&a [0];",5,false)` 函数`pointer_from_objref`获取julia对象的地址,因此在这些情况下通常不是你想要的.`&a [0]`在c ++中已经返回了你想要的指针; `pointer_from_objref`将为您提供表示该指针的julia对象的地址.经验法则是,如果你已经有一个指针,不要调用`pointer_from_objref`. (2认同)