Hi David,
"David Lowndes" <Da****@example.invalidwrote in message
news:hq********************************@4ax.com...
As long as you are using safe_cast and static_cast, not reinterpret_cast
or
old-style casts, the compiler should protect you.
In the attempt I had, I couldn't even fool it with those - though I
didn't try too hard. Let me rephrase that - I could get something to
compile with the heavy handed casts - but not something that worked.
What I couldn't do was get something to compile that worked (and would
have been susceptible to the managed heap movements that pin_ptr
prevents) - it was those specific situations I was worried about since
they'd pass casual tests but would likely fail in weird unpredictable
ways in the real world.
Dave
I do not necessarily agree with the other statements. IMO there *is* a need
for special care with pin pointers:
Let's start with a dumb scenario:
unsigned char* NeverDoThis(array<unsigned char>^ arr)
{
pin_ptr<unsigned charpp(&arr[0]);
return pp;
}
In this case, you pin a pointer to a managed array, use the standard
conversion to get a native pointer, and return the native pointer to the
caller. After the method has returned, the array is no longer pinned and
could be relocated, but the native pointer would still refer to the old
location. Let's have a look at a less dumb scenario:
Assume you have a managed array:
array<unsinged char>^ arr = GetArrayFromSomeWhere();
Further assume you want to pass a native pointer to the array to a native
function like this one:
void DoSth(unsigned char*);
To achieve this, you could write:
{
pin_ptr<unsigned charpp(&arr[0]);
DoSth(pp);
}
Is this code safe? Well that depends on the implementation of DoSth. If
DoSth stores the native pointer to access the array after the call, this
code as a problem, because the pinnng time ends after the pointer left
scope.
Marcus Heege