Hello everyone.
I am trying to write bindings for a C++ class which contains, among other stuff, a C++ std::vector that stores another std::vector inside. I want to access this std::vector from nim. I wrote the corresponding type declarations in nim. The nim compiler compiles everything without complaining but the cpp compiler from the cpp backend throws the error message: error: ... was not declared in this scope. I am using the CppVector from the nim-cppstl bindings to the C++ STL (https://github.com/Clonkk/nim-cppstl/tree/master).
I made a stripped down dummy example:
{.emit: """
#include <vector>
struct IntVector {
std::vector<int> numbers;
};
struct VectorFiller {
// fields
std::vector<IntVector> vectors; // a vector of IntVectors (nested vector)
// constructor
VectorFiller() { }
// getters
std::vector<IntVector> getVectors() { // get vector of vectors
return this->vectors;
}
IntVector getFirstVector() { // get first vector only
return this->vectors[0];
}
// methods
void fillVectors(int numVectors, int maxSize) { // fill vectors with garbage
for(int i = 0; i < numVectors; i++)
{
IntVector tmpVector;
for(int j = 0; j < maxSize; j++)
tmpVector.numbers.push_back(i + j);
this->vectors.push_back(tmpVector);
}
}
};
""".}
import cppstl/std_vector
# nim type declarations
type
IntVector* {.importcpp: "IntVector".} = object
numbers*: CppVector[cint]
type
VectorFiller* {.importcpp: "VectorFiller".} = object
vectors*: CppVector[IntVector]
# constructor
proc newVectorFiller*(): VectorFiller {.constructor, importcpp: "VectorFiller()", constructor.}
# methods
proc getVectors*(vectorFiller: VectorFiller): CppVector[IntVector] {.importcpp: "#.getVectors()".}
proc getFirstVector*(vectorFiller: VectorFiller): IntVector {.importcpp: "#.getFirstVector()".}
proc fillVectors*(vectorFiller: var VectorFiller; numVectors: cint; maxSize: cint) {.importcpp: "#.fillVectors(@)".}
# main procedure
proc main() =
# create a new vectorFiller
var vectorFiller: VectorFiller = newVectorFiller()
# fill vector with more or less random garbage (for demo only)
vectorFiller.fillVectors(cint(3), cint(4))
# getting a single (non nested) vector works like a charm
let firstVector: IntVector = vectorFiller.getFirstVector()
echo "firstVector no. of elements: ", firstVector.numbers.len()
echo "firstVector.numbers[2] = ", firstVector.numbers[2]
# let's try using the vectorFillers object attributes directly
# -> does not work -> cpp compiler error:
# error: 'IntVector' was not declared in this scope
let vectors: CppVector[IntVector] = vectorFiller.vectors
# let's try the getters
# again does not work, same error:
# error: 'IntVector' was not declared in this scope
let vectors_via_getter: CppVector[IntVector] = vectorFiller.getVectors()
# start main proc
main()
What i am doing wrong here?
Thank you very much in advance.
Thank you very much mashingan!
Everything works now flawlessly!