Possible to elegantly convert std:vector to cliext::vector or cli::array<T>?
How's that for a catchy title?
I need to convert back and forth from a CLR compliant type, like an array, and a std::vector type.
Are there any adapter methods out there, or should I just keep copying it in and out each time I call one of my native methods?
There are some interesting methods for converting between the cliext STL variant classes and CLR types, but I'm at a loss for how to get the standard vector into the STL types without a for next loop.
This is what I'm doing all over the place in this project:
vector<double> galilVector = _galilClass->arrayUpload(marshal_as<string>(arrayName));开发者_Go百科
List<double>^ arrayList = gcnew List<double>();
// Copy out the vector into a list for export to .net
for(vector<double>::size_type i = 0; i < galilVector.size(); i++)
{
arrayList->Add(galilVector[i]);
}
return arrayList->ToArray();
Instead of "doing that all over the place", why don't you make that logic into a reusable function?
Something like
template<typename T>
generic<typename S>
std::vector<T> marshal_as(System::Collections::Generic::ICollection<S>^ list)
{
if (list == nullptr) throw gcnew ArgumentNullException(L"list");
std::vector<T> result;
result.reserve(list->Count);
for each (S& elem in list)
result.push_back(marshal_as<T>(elem));
return result;
}
Remember to use vector's swap
member function to quickly move the elements into the vector you want to hold them, if you just assign then a zillion copy constructors would be called.
IList<int>^ Loader::Load(int id)
{
vector<int> items;
m_LoaderHandle->Loader->Load(id, items);
cliext::vector<int> ^result = gcnew cliext::vector<int>(items.size());
cliext::copy(items.begin(), items.end(), result->begin());
return result;
}
You can try this:
cliext::vector<Single> vec_cliext;
std::vector<float> vec_std;
cliext::vector<Single>::iterator it = vec_cliext.begin();
for (; it != vec_cliext.end(); ++it)
{
float temp = *it;
vec_std.push_back(temp);
}
精彩评论