Hi David,
> >As long as you are using safe_cast and static_cast, not reinterpret_cast
> >or
[quoted text clipped - 11 lines]
>
> 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 char> pp(&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 char> pp(&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
David Lowndes - 13 May 2007 22:55 GMT
Hi Markus,
Thanks for the comments.
>Let's start with a dumb scenario:
I sincerely hope we don't have any of those :) I'm pretty sure we
don't in fact.
>Assume you have a managed array:
>...
[quoted text clipped - 7 lines]
>code as a problem, because the pinnng time ends after the pointer left
>scope.
Yeah, they're both examples of the same situation really - using the
pinned native pointer outside the pinning scope.
I was really more concerned with any more direct situations where you
could fail to use pin_ptr where it was really necessary.
The first example is fairly easy to check for, but as you say the
second one isn't (as we're using a 3'rd party library that we don't
have the source to).
Are there any diagnostic tools that would help flush out problems
where the managed heap moves? Something that explicitly causes lots of
managed heap movements?
Dave