Garbage collection should not concern you, since you object is pinned automatically as soon as you pass it to the method (source: MSDN):
When the runtime marshaler sees that your code is passing to native code a reference to a managed reference object, it automatically pins the object.
In case that your native method saves the reference (pointer) for some later async work, you must pin it manually:
byte[] b = new byte[1024];
GCHandle pinHandle = GCHandle.Alloc(b, GCHandleType.Pinned);
try
{
someObject.GetBinData(ref b[0], b.length);
}
finally
{
pinHandle.Free();
}
Otherwise, there is no reason why it shouldn't work. You are allocating the memory before calling the method, CLR pins your object until the method is executed, and your native code should take care that array length is taken into account.
Groo
2010-07-16 06:59:19