将C++类移植到ref类(从非托管到托管)

Porting a C++ class to a ref class (unmanaged to managed)

本文关键字:ref C++      更新时间:2023-10-16

我有一个非托管类,我从C++Windows窗体(托管类)调用它。但是,我想将这个类重写为ref类,但我不知道如何处理在非托管类中声明的全局数组成员。

作为一个例子,我写了一个非常简单的类,它以某种方式展示了我需要做什么

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;
}

在这里,我有一个全局成员数组,我希望能够从类中的所有函数访问它。

在windows窗体中,我有一个按钮和一个组合框。这样,当按下按钮时,它只调用类中的函数并显示结果。

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();
}

现在,如果我试图将类更改为ref类,则会出现错误,因为全局数组处于非托管状态。我试着用std::vectors来做这件事,这是一种比直接使用数组更好的方法,但会得到同样的错误。因此,如果有人能给我一种将这个类重写为ref类的方法,我将不胜感激。非常感谢。

我认为'global'这个词不适合用于非托管数组,因为它包含在非托管类定义中。非托管数组也没有static关键字,因此它是一个实例变量,远不是全局变量。

无论如何,您遇到的问题似乎是数组定义。int myArray[5][24]是非托管的"对象",不能直接包含在托管类中。(可以有指向非托管对象的指针,但不能有内联非托管对象。)可以将其切换为指向整数数组的指针,并处理malloc&免费,但使用托管阵列要简单得多。

以下是将该数组声明为托管的语法:

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;
    }
};

数组类是根据数据类型和维度数量模板化的,因此对于整数的2D数组,array<int, 2>就是您想要的。