This is a Windows Forms Application project using Visual Studio 2010. That being said:
I’ve an unmanaged ‘Vector’ implementation, something like:
template<class T>
class Vector {
public:
T* data;
unsigned len;
(...constructors and operators overloading like =, [], == and !=)
};
It works great. I’ve done several tests before with it. After that I’ve implemented an also unmanaged ‘Matrix’ that uses the previously class Vector. Something like:
template<class T>
class Matrix : public Vector<Vector<T>*> {
public:
Matrix(unsigned height = 20, unsigned width = 20)
: Vector(height)
{
for (unsigned i = 0; i < height; i++) {
data[i] = new Vector<T>(width);
}
}
Vector<T> operator[](unsigned pos) {
return data[pos];
}
};
It also works great but with unmanaged data as T. My main objective, access data using [][], worked as expected.
But now I want to use this Matrix class inside managed code, with data T also being managed code, in this case a ‘Cell’ already implemented:
public ref class Cell {
public:
bool dead;
public:
Cell() {
this->dead = false;
}
Cell(bool dead) {
this->dead = dead;
}
virtual String^ ToString() override {
return (this->dead ? "0" : "1");
}
};
I’m doing the initialization this way:
Matrix<gcroot<Cell^>>* cells = new Matrix<gcroot<Cell^>>(height, width);
for (unsigned i = 0; i < height; i++) {
for (unsigned j = 0; j < width; j++) {
gcroot<Cell^> * cell = new gcroot<Cell^>;
cells[i][j] = cell; // ERROR!!
}
}
The line where I assign the cell to matrix always returns the error in the title. Other operators (aside from ‘=’) also gives me the same error.
I’ve tried everything but I can’t find a way to fix this. I’m really avoiding to touch Vector and Matrix classes because they’ve to be unmanaged and I’ve to use gcroot to inject managed data inside it.
At the end of the day, Cell will be a System::Windows::Forms::Button so the implementation has to be this way.
Any ideas? Sorry if I was unable to explain myself. If you need more code from Vector class please tell. Thanks is advanced 🙂
Honestly, you are going to have to do a lot of work to use this native C++ code direct from managed code (if it’s even possible).
It’s probably going to be easier to reimplement it in STL/CLR, if you need to stick with C++, or in C# if not. The mere existence of this STL/CLR class library should tell you something about how advisable it is to use native C++ STL containers in this way.
EDIT:
You can probably fix the compilation error by using
Your
operator[]should not return by value, or the underlyingVectorelement will not be altered as you will be working with a copy of what’s in theMatrix.Comments about this being non-trivial stand.