4

在 C++/CLI 中,不能将指向本机 C++ 类的指针放在托管的 .NET 泛型集合中,例如

class A {
public:
    int x;
};

public ref class B {
public:
    B()
    {
        A* a = GetPointerFromSomewhere();
        a->x = 5;
        list.Add(a);
    }
private:
    List<A*> listOfA; // <-- compiler error (T must be value type or handle)
}

不被允许。我当然可以使用std::vector<A*> list;,但是我只能list通过使用指针来创建托管类的成员,并且使用指向 STL 容器的指针感觉不自然。

在 .NET 泛型中存储本机 C++ 指针的好方法是什么?(我对这里的资源管理不感兴趣;指针指向的对象在别处管理)

4

1 回答 1

7

我一直使用的方法是将指针包装在托管值类中,然后重载解引用运算符:

template<typename T>
public value class Wrapper sealed
{
public:
    Wrapper(T* ptr) : m_ptr(ptr) {}
    static operator T*(Wrapper<T>% instance) { return instance.m_ptr; }
    static operator const T*(const Wrapper<T>% instance) { return instance.m_ptr; }
    static T& operator*(Wrapper<T>% instance) { return *(instance.m_ptr); }
    static const T& operator*(const Wrapper<T>% instance) { return *(instance.m_ptr); }
    static T* operator->(Wrapper<T>% instance) { return instance.m_ptr; }
    static const T* operator->(const Wrapper<T>% instance) { return instance.m_ptr; }
    T* m_ptr;
};

然后我可以自然地使用指针如下:

public ref class B {
public:
    B()
    {
        A* a = GetPointerFromSomewhere();
        a->x = 5;
        list.Add(Wrapper<A>(a));
        Console.WriteLine(list[0]->x.ToString());
    }
private:
    List<Wrapper<A>> listOfA;
}

欢迎任何改进...

于 2012-07-03T09:47:16.147 回答