What is pinned exactly?

P

Pierre

Hi everyone;

I have a class with several members and I pin the first reference field in a
function;

public ref struct MyClass
{
String str1;
List<MySubClass ^> ^subObjects;
....
};

void ManagedFunc(MyClass ^class)
{
pin_ptr<const wchar_t> s1 = PtrToStringChars(class->str1);

.....
}

Now the first question is; which objects are pinned? MSDN documentation says
"Pinning a sub-object defined in a managed object has the effect of pinning
the entire object." But what does "the entire object" mean? Is it just str1
and MyClass? Or are the subObjects list and the elements contained in it
also pinned? Does the runtime pin each and every object that can be reached
from the parent object?

A second question. Why is it not possible to pin a reference type directly
using pin_ptr? Like;

pin_ptr<MyClass ^> pS = gcnew MyClass();

With GCHandle it's possible to directly pin an object, but as far as I
understand pin_ptr does not allow this semantic.

Regards...
 
B

Ben Voigt

Pierre said:
Hi everyone;

I have a class with several members and I pin the first reference field in
a function;

public ref struct MyClass
{
String str1;
List<MySubClass ^> ^subObjects;
....
};

void ManagedFunc(MyClass ^class)
{
pin_ptr<const wchar_t> s1 = PtrToStringChars(class->str1);

.....
}

Now the first question is; which objects are pinned? MSDN documentation
says "Pinning a sub-object defined in a managed object has the effect of
pinning the entire object." But what does "the entire object" mean? Is it
just str1

A reference type, such as System::String, can never be a sub object. The
only object that gets pinned is the string instance referenced by str1.

Also, you should please avoid abusing keywords such as class, if you expect
people to take your example code seriously.
and MyClass? Or are the subObjects list and the elements contained in it
also pinned? Does the runtime pin each and every object that can be
reached from the parent object?

Even if you had pinned the parent object, by using a pinning pointer to a
value type (value typed member variables actually are sub-objects), then
only the parent object would be pinned. Reachable objects are not affected,
since the garbage collector can still update the parent object to point to
the new location of the other instances, just not move the parent itself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top