在C++/CLI中,不可能将指针放在托管.NET泛型集合中的本机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)
}
Run Code Online (Sandbox Code Playgroud)
不被允许.我当然可以使用std::vector<A*> list;但是后来我只能list通过使用指针来创建托管类的成员,并且使用指向STL容器的指针感觉不自然.
在.NET泛型中存储本机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;
};
Run Code Online (Sandbox Code Playgroud)
然后我可以自然地使用指针如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
欢迎任何改进......
| 归档时间: |
|
| 查看次数: |
1440 次 |
| 最近记录: |