在 C++/CLI 中将 std::vector<>::iterator 转换为 .NET 接口
-
01-07-2019 - |
题
我正在包装一个本机 C++ 类,它具有以下方法:
class Native
{
public:
class Local
{
std::string m_Str;
int m_Int;
};
typedef std::vector<Local> LocalVec;
typedef LocalVec::iterator LocalIter;
LocalIter BeginLocals();
LocalIter EndLocals();
private:
LocalVec m_Locals;
};
1) 表示同一类型接口的“.NET 方式”是什么?返回数组 <> 的单个方法?array<> 泛型是否具有迭代器,以便我可以实现 BeginLocals() 和 EndLocals()?
2) Local 是否应该被声明为 值结构 在.NET 包装器中?
我真的很想用 .NET 风格来表示包装类,但我对托管世界非常陌生 - 而且这种类型的信息对于谷歌来说是令人沮丧的......
解决方案
迭代器并不完全可以翻译为“.net 方式”,但它们大致被 IEnumerable < T > 和 IEnumerator < T > 取代。
而不是
vector<int> a_vector;
vector<int>::iterator a_iterator;
for(int i= 0; i < 100; i++)
{
a_vector.push_back(i);
}
int total = 0;
a_iterator = a_vector.begin();
while( a_iterator != a_vector.end() ) {
total += *a_iterator;
a_iterator++;
}
你会看到(在c#中)
List<int> a_list = new List<int>();
for(int i=0; i < 100; i++)
{
a_list.Add(i);
}
int total = 0;
foreach( int item in a_list)
{
total += item;
}
或者更明确地(不将 IEnumerator 隐藏在 foreach 语法糖后面):
List<int> a_list = new List<int>();
for (int i = 0; i < 100; i++)
{
a_list.Add(i);
}
int total = 0;
IEnumerator<int> a_enumerator = a_list.GetEnumerator();
while (a_enumerator.MoveNext())
{
total += a_enumerator.Current;
}
正如您所看到的,foreach 只是为您隐藏了 .net 枚举器。
所以实际上,“.net 方式”就是简单地允许人们为自己创建 List<Local> 项目。如果您确实想控制迭代或使集合更加自定义,请让您的集合也实现 IEnumerable< T > 和/或 ICollection < T > 接口。
几乎直接翻译成 c# 几乎就是您所假设的:
public class Native
{
public class Local
{
public string m_str;
public int m_int;
}
private List<Local> m_Locals = new List<Local>();
public List<Local> Locals
{
get{ return m_Locals;}
}
}
然后用户将能够
foreach( Local item in someNative.Locals)
{
...
}
其他提示
@Phillip - 谢谢,你的回答确实让我朝着正确的方向开始。
看到你的代码并阅读 Nish 的书之后 C++/CLI 实际应用, ,我认为使用索引属性将常量跟踪句柄返回到托管堆上的本地实例可能是最好的方法。我最终实现了类似于以下内容的内容:
public ref class Managed
{
public:
ref class Local
{
String^ m_Str;
int m_Int;
};
property const Local^ Locals[int]
{
const Local^ get(int Index)
{
// error checking here...
return m_Locals[Index];
}
};
private:
List<Local^> m_Locals;
};
不隶属于 StackOverflow