Groups | Blog | Home
all groups > dotnet interop > november 2006 >

dotnet interop : Using IntPtr help


Andre Azevedo
11/8/2006 9:20:24 PM
Hi all,

I need to call an unmanaged function that accepts a void* parameter.
To call the function I use an IntPtr object using Marshal.AllocHGlobal:

[DllImport ...]
public static extern int ExampleFunction(IntPtr p, ref int size);
....
int size = 0;
IntPtr p = Marshal.AllocHGlobal(512);
ExampleFunction(p, ref size);

Question 1
Is IntPtr pinned? I need to use GCHandle to pass the IntPtr parameter?

Question 2
After p is filled I use Marshal.PtrToStructure to marshal IntPtr to a
managed structure. After call PtrToStructure can I dispose the IntPtr using
FreeHGlobal? Does the managed structure variable still points to IntPtr
value?

TIA!

--
Andre Azevedo



Mattias Sjögren
11/9/2006 12:00:00 AM
Andre,

[quoted text, click to view]

It doesn't have to be pinned since it's a value type instance
allocated on the stack.


[quoted text, click to view]

Yes


[quoted text, click to view]

No, managed instances are always allocated on the GC heap or stack,
not on a native heap.


Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
AddThis Social Bookmark Button