Sometimes, a C/C++ function needs to store data you pass to it for later reference. If such data is a managed object (like a string
or class
), you need to make sure that the garbage collector doesn’t delete it while it’s still in use/still stored in the native code.
That’s what pinning is for. It prevents the garbage collector from deleting and moving the object.
Pinning an Object
To pin a managed object, use GCHandle.Alloc()
:
GCHandle handle = GCHandle.Alloc(objectToBePinned, GCHandleType.Pinned);
The objectToBePinned
remains pinned until you call Free()
on the handle:
handle.Free();
After unpinning the object, it can again be:
- moved by the garbage collector (to optimize the memory)
- deleted, if no more references exist to it
Notes
Free()
will never be called automatically. If you don’t call it manually, the memory of the pinned object will never be freed (i.e., you create a memory leak). - You only need to pin objects (including
string
s). You can’t pin primitive types (like int
) and structs, as they reside on the stack and are passed by copy. If you try pin a struct
, a copy of the struct
will be pinned. - Classes and
struct
s must have the attribute [StructLayout(LayoutKind.Sequential)]
to control the layout of their fields. Otherwise, GCHandle.Alloc()
will throw an ArgumentException
reading: “Object contains non-primitive or non-blittable data.
” -
If the method you’re calling doesn’t store a reference to the passed object for later reference, you don’t need to pin this object. P/Invoke automatically pins objects before the C/C++ function is called and unpins them after the function has returned. So, manually pinning an object is actually about the (time of) unpinning.
Passing a Pinned Object
Now that you’ve pinned your object, you surely want to pass it to a C/C++ function.
The easiest way to do this is to specify managed type directly on the P/Invoke method:
[DllImport("NativeLib")]
private static extern void do_something(MyType myType);
Then call this method:
GCHandle handle = GCHandle.Alloc(objectToBePinned, GCHandleType.Pinned);
do_something(objectToBePinned);
handle.Free();
The alternative is to pass it as IntPtr
(although it’s no different from the direct approach):
[DllImport("NativeLib")]
private static extern void do_something(IntPtr myType);
...
GCHandle handle = GCHandle.Alloc(objectToBePinned, GCHandleType.Pinned);
do_something(objectToBePinned.AddrOfPinnedObject());
handle.Free();
Pinning and Passing Strings
Pinning string
s is the same as pinning objects with one exception:
You must specify the CharSet.Unicode
. when passing pinned strings.
Otherwise, P/Invoke will convert the string
into an ASCII string
(thereby copying it).
Assume this C function:
void do_something(void* str1, void* str2) {
printf("Equals: %s\n", (str1 == str2 ? "true" : "false"));
}
Then:
[DllImport("NativeLib", EntryPoint="do_something")]
private static extern void do_something1(string str1, IntPtr str2);
[DllImport("NativeLib", CharSet = CharSet.Unicode, EntryPoint="do_something")]
private static extern void do_something2(string str1, IntPtr str2);
...
string text = "my text";
GCHandle handle = GCHandle.Alloc(text, GCHandleType.Pinned);
do_something1(text, handle.AddrOfPinnedObject());
do_something2(text, handle.AddrOfPinnedObject());
Verifying the Pinned Object is Passed
As mentioned in the previous section, P/Invoke may create a copy of an object instead of passing it by reference directly.
You can easily verify this by comparing the pointer addresses. In C#, use handle.AddrOfPinnedObject().ToString()
to obtain the address of the pinned object.
CodeProject