pinning member of struct -> entire struct pinned?

B

Ben Schwehn

If I pin a member of a garbage collected structure, can I safely assume
that the entire struct is pinned?

I use something like that: (new whidbey syntax, but that shouldn't make
a difference):



[StructLayout(LayoutKind::Sequential)]
public ref struct MyStruct {
Int32 memberA;
Int16 memberB;
Int32 memberC;
}
....

MyStruct^ struct = gcnew MyStruct();
void* pData = somedata_somwhere;

//pData points to a memory location,
//that holds data not only about
//memberA but also memberB and memberC


pin_ptr<int> pMemberA = &struct->membera;
memcpy((void*)pMemberA, pData, sizeofdata);
pMemberA = nullptr;


it works but is it correct?
Would it also be correct if i hadn't specified LayoutKind::Sequential?

Thanks
Ben
 
B

Ben Schwehn

Would it also be correct if i hadn't specified LayoutKind::Sequential?
Replying to myself:
Well, since memberA is not guranteed to be the first member in memory, I
suppose it wouldn't be correct to use a pointer to memberA as a pointer
to the struct.
Still, could the GC potentially shift other members around if only one
member is pinned and the LayoutKind is not specified?

I know that when you pin a member of an array, the entire array gets
pinned.
 
R

Ronald Laeremans [MSFT]

No, pinning any member will pin the entire object. That is a hard guarantee
that the CLI spec makes.

Practically in the current CLR implementation, different parts do not move
independently or get rearranged at all. Future implementations might in fact
start doing this, so you were correct to think of this possibility.

Ronald Laeremans
Visual C++ team
 

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

Similar Threads


Top