转换std :: vector< T>的最有效方法是什么到.NET List< U> ;? [英] What is the most efficient way to convert a std::vector<T> to a .NET List<U>?
问题描述
将std :: vector转换为.NET列表的最有效方法是什么?
What is the most efficient way to convert a std::vector to a .NET List?
为了提供一些背景信息,我使用了一个非托管C ++类C ++ / CLI。 C ++ / CLI类包含一个指向C ++类的指针,每个公共方法都有一个包装器。
To give some context, I am wrapping an unmanaged C++ class with C++/CLI. The C++/CLI class holds a pointer to the C++ class and I have a wrapper for each public method.
一个方法返回一个std :: vector,因此在我的包装器中我打算返回.NET类列表。即
One method returns a std::vector, so in my wrapper I was going to return the .NET class List. I.e.
// unmanaged class
class A
{
public:
std::vector<int> runList();
}
// managed class
public ref class A
{
public:
// the below is obviously extremely inefficient
List<UInt32> MethodA()
{
std::vector<unsigned int> runList = mpChannelNode->runList();
std::vector<unsigned int>::iterator itr;
List<UInt32> list = gcnew List<UInt32>();
for (itr = runList.begin(); itr != runList.end(); itr++)
{
list.Add(*itr);
}
return list;
}
private:
A* mpChannelNode;
}
如何提高效率?随时为.NET类推荐其他返回类型。假设我只是需要以任何形状或形式将向量有效地带入管理的世界中。
How can I make this more efficient? Feel free to recommend a different return type for the .NET class. Lets assume I just need to get that vector into managed world efficiently in any shape or form.
推荐答案
如果您真的对此担心,请改用不可验证的代码:
If you're really that concerned about it, use unverifiable code instead:
List<unsigned>^ MethodA()
{
std::vector<unsigned> const& runList = mpChannelNode->runList();
array<unsigned>^ ret = gcnew array<unsigned>(runList.size());
if (runList.size())
{
pin_ptr<unsigned> dest = &ret[0];
std::memcpy(dest, &runList[0], runList.size() * sizeof(unsigned));
}
return gcnew List<unsigned>(ret);
}
话虽如此,如果两种方式之间都存在明显差异,我会感到惊讶...
That said, I'd be surprised if there was a noticeable difference either way...
这篇关于转换std :: vector< T>的最有效方法是什么到.NET List< U> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!