are value types guaranteed to be "pinned"

  • Thread starter Thread starter Mark Oliver
  • Start date Start date
M

Mark Oliver

Hi,

I want to pass a reference to a char type to a class constructor, then
read/write to the passed char later in my code. Are the below Asserts
right?

Thanks,
Mark


public class pinTest

{

private IntPtr ip;

public pinTest(ref char ch)

{

unsafe

{

fixed(void *vp=&ch)

ip=new IntPtr(vp); // is ip valid after fixed statement if
'ch' was value type?

}

}

public char c

{

set

{

unsafe

{

*((char *)(ip.ToPointer()))=value;

}

}

get

{


unsafe

{

return *((char *)(ip.ToPointer()));

}

}

} // public char c

} // class pinTest

public void Main()

{

char a='a';

pinTest pa=new pinTest(ref a);

char [] cb={'b'};

pinTest pb=new pinTest(ref cb[0]);

/*

..

..

..

*/

Trace.Assert(a==pa.c,"Pass because 'a' was value type?");

Trace.Assert(cb[0]==pb.c,"maybe Fail because 'cb' was reference type?");

}
 
Mark,
I want to pass a reference to a char type to a class constructor, then
read/write to the passed char later in my code. Are the below Asserts
right?

Yes you're right. The a char is located on the stack an will not be
moved by a GC, so it's safe to keep a pointer to it as long as the
Main stack frame exists.

It's not safe to keep a pointer to an item in the cb array unless you
make sure the array is pinned for as long as you need the pointer.



Mattias
 
Thanks very much, I will sleep better.

Mattias Sjögren said:
Mark,


Yes you're right. The a char is located on the stack an will not be
moved by a GC, so it's safe to keep a pointer to it as long as the
Main stack frame exists.

It's not safe to keep a pointer to an item in the cb array unless you
make sure the array is pinned for as long as you need the pointer.



Mattias
 
Back
Top