pinning types via 'Fixed'

  • Thread starter Thread starter Chris Finlayson
  • Start date Start date
C

Chris Finlayson

Hello:

I have a question on pinning types via 'fixed'. In "Com and .NET
interoperability" by Andrew Troelsen, he provides a simple example of
..NET -> Native interoperability:

int[] theVals={1,2,3,4};
MyCustomDLLWrapper.AddArray(theVals,theVals.Length)

where MyCustomDLLWrapper wraps a native (C++) .dll:

public class MyCustomDLLWrapper
{
[DllImport("MyCustomDll.dll")]
public static extern int AddNumbers(int x[], int size);
}

Where AddNumbers is defined (obviously) in MyCustomDll.dll

Now, for correctness, shouldn't he be locking the reference to the
array in memory so it isn't garbage collected? So, shouldn't it be:

int[] theVals={1,2,3,4};
fixed(int* pinnedAry = theVals)
{
MyCustomDLLWrapper.AddArray(pinnedAry,theVals.Length)
}

?

Thanks!

Chris Finlayson
 
I have a question on pinning types via 'fixed'. In "Com and .NET
interoperability" by Andrew Troelsen, he provides a simple example of
.NET -> Native interoperability:

int[] theVals={1,2,3,4};
MyCustomDLLWrapper.AddArray(theVals,theVals.Length)

where MyCustomDLLWrapper wraps a native (C++) .dll:

public class MyCustomDLLWrapper
{
[DllImport("MyCustomDll.dll")]
public static extern int AddNumbers(int x[], int size);
}

Where AddNumbers is defined (obviously) in MyCustomDll.dll

Now, for correctness, shouldn't he be locking the reference to the
array in memory so it isn't garbage collected? So, shouldn't it be:

int[] theVals={1,2,3,4};
fixed(int* pinnedAry = theVals)
{
MyCustomDLLWrapper.AddArray(pinnedAry,theVals.Length)
}


The array cannot be garbage collected since there is still a refererence on
it. But it might be moved in memory when not beeing fixed so it is IMHO
always nesseccary to fix objects when passing them to native functions.
 
Arrays of blittable types are automatically pinned by the P/Invoke
infrastructure when you pass them to unmanaged export functions.
However, they are only pinned for the duration of the call.

-Rob Teixeira [MVP]
 
Back
Top