Sunday, December 28, 2008

Interoperating with COM - Using COM from the .NET Framework (4)

How to Pass Structures to unmanaged functions

When you called unmanaged functions in managed code, you might need to pass structures as parameters. Typically, the CLR controls the physical layout of the data fields of a class or structure in managed memory. However, sometimes, you might need to specify the layout of a structure when passing it, and you can do that by using the StructLayout and FieldOffset attributes. (Both are in the namespace "System.Runtime.InteropServices")

Whe using StructLayout attribute, the LayoutKind.Sequential is used to force the data members to be laid out sequentially in the order they appear. You also can use LayoutKind.Explicit to control precise position of each data member by applying FieldOffset attribute to each data member. If you want to give CLR full cotrol of the layout and the sequence of the fields, you can use LayoutKind.Auto instead.

Here is an example:
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public struct Point{
public int x;
public int y;
}

[StructLayout(LayoutKind.Explicit)]
public struct Rect{
[FieldOffset(0)]public int left;
[FieldOffset(4)]public int top;
[FieldOffset(8)]public int right;
[FieldOffset(12)]public int bottom;
}

class Example()
{
[DllImport("user32.dll")]
public static extern bool PtInRect(ref Rect r, Point p);
}

Here is the reference link from MSDN about StructLayoutAttribute:
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx

No comments:

Post a Comment