Reputation: 7007
I have managed class with function:
int DoSomething(cli::array<int>^ values) { .. }
In DoSomething I must call native function:
template <class It>
int Calculate(It beg, It end) {..}
Which iterator to use?
Upvotes: 3
Views: 1379
Reputation: 17444
You'll want to use a pinning pointer to the managed array. This will fix the array in memory (i.e. make it so the garbage collector can't move it) and then you can treat it as a native array. Below is a sample using your methods.
Take note, that you need to finish using the array before the pinning pointer goes out of scope--once the pinning pointer goes out of scope, the managed array is no longer pinned, and the garbage collector is free to move the array.
Also, take note that pinning the first element of the array causes the entire managed array to be pinned (in general using a pinning pointer on one part of a managed object causes the entire managed object to be pinned).
template <class It> int Calculate(It beg, It end)
{
int sum = 0;
for (; beg != end; ++beg)
{
int i = *beg;
sum += i;
}
return sum;
}
int DoSomething(cli::array<int>^ values)
{
int numValues = values->Length;
pin_ptr<int> pNativeValuesBegin = &values[0];
int * pBegin = pNativeValuesBegin;
int * pEnd = pBegin + numValues;
return Calculate(pBegin, pEnd);
}
int main(array<System::String ^> ^args)
{
array<int> ^ values = gcnew array<int> { 1, 2, 3, 4, 5 };
int sum = DoSomething(values);
System::Console::WriteLine(sum);
return 0;
}
Upvotes: 4