Friday, July 31, 2009

C# - C++ - [StructLayout] to pass structures to unmanaged function

CLR rearranges the order of type members during runtime, it generates better performance, faster access to members, less memory consumption, and so. But when .NET wants to interoperate with unmanaged codes, it's necessary to keep the structure layout as is. For this purpose, it's possible to specify the layout of a structure by using the StructLayout attribute.

[StructLayout(LayoutKind.Sequential)] keeps the sequence of members in structure type as defined. The following sample gets the OS version by passing a pointer to structure to GetVersionEx function in unmanaged kernel32.dll:

...
using System.Runtime.InteropServices;
...
[DllImport("kernel32.dll")]
public static extern
bool GetVersionEx(ref OSVERSIONINFO lpVersionInfo);

[StructLayout(LayoutKind.Sequential)]
public struct OSVERSIONINFO
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public String szCSDVersion;
}
...
OSVERSIONINFO osVer = new OSVERSIONINFO();
osVer.dwOSVersionInfoSize = Marshal.SizeOf(osVer);
string osVersion = string.Empty;

if (GetVersionEx(ref osVer))
osVersion = string.Format("{0}.{1}.{2}",
osVer.dwMajorVersion,
osVer.dwMinorVersion,
osVer.dwBuildNumber);

MessageBox.Show("OS Ver: " + osVersion);

OSVERSIONINFO Structure
http://msdn.microsoft.com/en-us/library/ms724834(VS.85).aspx
Share/Bookmark

No comments: