gpt4 book ai didi

c++-cli - 我应该如何将 native C++ 指针放入 .NET 泛型集合中?

转载 作者:行者123 更新时间:2023-12-04 23:59:54 24 4
gpt4 key购买 nike

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

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 泛型中存储 native C++ 指针的好方法是什么? (我对这里的资源管理不感兴趣;指针指向的对象在别处管理)

最佳答案

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

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

欢迎任何改进...

关于c++-cli - 我应该如何将 native C++ 指针放入 .NET 泛型集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11308340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com