Brian said:
I have a situation where I have a vector<gcroot<ManagedWrapperClass*> >
whose contents I need to pass to an unmanaged function. Is there a way
to pin all the pointers in the vector for that function? I tried to
copy the vector into another vector with a pinned pointer type, but the
compiler will not allow __pin to be used in a template parameter.
Thanks!
From the VC++ 2005 help:
<quote>
Pinning a sub-object defined in a managed object has the effect of
pinning the entire object. For example, if any element of an array is
pinned, then the whole array is also pinned.
// pin_ptr_array.cpp
// compile with: /clr
#include <stdio.h>
using namespace System;
int main() {
array<Byte>^ arr = gcnew array<Byte>(4);
arr[0] = 'C';
arr[1] = '+';
arr[2] = '+';
arr[3] = '0';
pin_ptr<Byte> p = &arr[1]; // entire array is now pinned
unsigned char * cp = p;
printf_s("%s\n", cp); // bytes pointed at by cp
// will not move during call
}
</quote>
I'm not sure if this is true for VC++ 2003 (MC++ syntax), but I think it is.
Is it possible that you change your design and instead of storing an
unmanaged STL vector<gcroot<ManagedWrapperClass*> >, you could be
storing your managed classes in a managed array. I think it would be
doable, and gcroot the entire managed array. That way if you pin the
first item in the array, the entire array will be pinned. Just an idea.
Maybe someone else has a better recommendation.
On the other hand, I would be cautious about pinning a managed class.
Are you sure that an unmanaged code can interpret the internals of a
managed class? Is your managed class byte-compatible with an unmanaged
data structure? How are the member variables aligned inside? I may be
wrong, but I've only pinned managed byte arrays and integer arrays,
because I know they're byte-compatible with their unmanaged counterparts.
Tom