itun
itun

Reputation: 3521

Get pointer (IntPtr) of int value

How I can get an Intptr pointer of integer value?

I was trying to do that it work. Are any other variants?

GCHandle gCHandle = GCHandle.Alloc (size, GCHandleType.Pinned);
IntPtr sizePtr = gCHandle.AddrOfPinnedObject ();

Upvotes: 3

Views: 4987

Answers (1)

Hans Passant
Hans Passant

Reputation: 941675

Only objects of a reference types can be pinned, int is a value type.

You can get a pointer to an int that's a local variable in a method:

unsafe void foo() {
   int value = 42;
   int* ptrToValue = &value;
   // etc, do not return the pointer!!
   //...
}

Upvotes: 6

Related Questions