I am new to Julia and and I am trying to access my C++ code from Julia. More precisely, I am trying to call a C++ function from Julia using Cxx. The input and output parameters of the C++ function are std::vectors, see the function compute_sum in the example below:
#include <vector>
#include <iostream>
std::vector< int > compute_sum( const std::vector< std::vector<int> >& input )
{
std::vector< int > resut( input.size() , 0 );
for ( std::size_t i = 0 ; i != input.size() ; ++i )
{
for ( std::size_t j = 0 ; j != input[i].size() ; ++j )
{
resut[i] += input[i][j];
}
}
return resut;
}
void simple_function( int i )
{
std::cout << "The numbers is : " << i << std::endl;
}
Assuming this function is stored as code.cpp I am compiling it to a shared object code.so using:
g++ -shared -fPIC code.cpp -o code.so
and as a result I obtain a file code.so
Having this, I run Julia in the same folder as code.so. My version of Julia is 0.6.2. Then I import Cxx and the code.so file using:
julia> using Cxx
julia> const path_to_lib = pwd()
julia> addHeaderDir(path_to_lib, kind=C_System)
julia> Libdl.dlopen(path_to_lib * "/code.so", Libdl.RTLD_GLOBAL)
Ptr{Void} @0x00000000044bda30
julia> cxxinclude("code.cpp")
In odder to test if the process is successful I am calling the simple_function and obtain the correct results:
julia> @cxx simple_function(1234)
The numbers is : 1234
Then I want to call compute_sum function. For that I need somehow to create, or convert Julia vector into C++ std::vector< std::vector >. I am trying the following:
julia> cxx" std::vector< std::vector<int> > a;"
true
julia> icxx" a.push_back( std::vector<int>(1,2) ); "
julia> icxx" a.push_back( std::vector<int>(1,3) ); "
julia> icxx" a.push_back( std::vector<int>(1,4) ); "
julia> icxx" a.size(); "
0x0000000000000003
So I assume that the vector is created in a correct way. Then I trying to call the function with it, but I fail:
julia> @cxx compute_sum(a)
ERROR: UndefVarError: a not defined
julia> @cxx compute_sum("a")
ERROR: Got bad type information while compiling Cxx.CppNNS{Tuple{:compute_sum}} (got String for argument 1)
julia> icxx " compute_sum(a);"
ERROR: syntax: extra token """ after end of expression
Could anyone help me please with the following question(s):
- How to call compute_sum function from Julia? I am happy to use any technique (not necessary Cxx) that works and is reasonably fast.
- How to convert the result of compute_sum to Julia array?
Thank you very much!
pawel
g++ -shared -fPIC code.cpp -o code.so
" - there's some confusion here. You say you build a static library, but the-shared
compiler option says otherwise. Also, static libraries are usually named with a ".a" extension while ".so" is for shared libraries ("so" being short for "shared object"). So, what do you actually mean to do?vector
s insideinput
allowed to have differentsize
s? Plus, you seem to have a small glitch in your code --- the inner loop is also incrementingi
. Is this intended?