I have an unmanaged class, which I'm calling from a C++ Windows Form (managed class). However, I would like to re-write this class as a ref class, but I'm not sure how to deal with global array members that are declared within the unmanaged class.
As an example I wrote a very simple class, that shows somehow what I need to do.
public class test {
private:
int myArray[5][24];
public:
int assign(int i){
test::myArray[2][4] = i;
return 0;
}
int dosomething(int i){
return test::myArray[2][4] + i;
}
In here I have a global member array, which I want to be able to access from all the functions within the class.
In the windows form I have a button and a combo box. This way when the button is pressed it just calls the functions in the class and displays the results.
private: System::Void thumbButton_Click(System::Object^ sender, System::EventArgs^ e) {
test my_class;
my_class.assign(5);
comboBox1->Text = my_class.dosomething(6).ToString();
}
Now if I try to change the class to a ref class, there is an error because of the global array being unmanaged. I tried doing this with std::vectors, which is a better approach than using the array directly, but get the same error. Therefore, I would really appreciate if someone can point me to a way to rewrite this class as a ref class. Thank you!
I don't think 'global' is the right word for your unmanaged array, as it is contained within the unmanaged class definition. The unmanaged array doesn't have the static
keyword either, so it's an instance variable, which is nowhere near global.
Regardless, it seems the issue you're having is with the array definition. int myArray[5][24]
is an unmanaged 'object', which can't be directly included in your managed class. (You can have pointers to unmanaged objects, but not inline unmanaged objects.) You could switch that to a pointer to an integer array, and deal with malloc & free, but it's much simpler to go with a managed array instead.
Here's the syntax to declare that array as managed:
public ref class test
{
private:
array<int, 2>^ myArray;
public:
test()
{
this->myArray = gcnew array<int, 2>(5, 24);
}
int assign(int i)
{
this->myArray[2,4] = i;
return 0;
}
int dosomething(int i)
{
return this->myArray[2,4] + i;
}
};
The array class is templated on the data type and the number of dimensions, so for a 2D array of integers, array<int, 2>
is what you want.