Jump to content

C# Programming/The .NET Framework/Marshalling

From Wikibooks, open books for an open world

The .NET Framework currently supports calling unmanaged functions and using unmanaged data, a process called marshalling. This is often done to use Windows API functions and data structures, but can also be used with custom libraries.

GetSystemTimes

[edit | edit source]

A simple example to start with is the Windows API function GetSystemTimes. It is declared as:

BOOLWINAPIGetSystemTimes(__out_optLPFILETIMElpIdleTime,__out_optLPFILETIMElpKernelTime,__out_optLPFILETIMElpUserTime);

LPFILETIME is a pointer to a FILETIME structure, which is simply a 64-bit integer. Since C# supports 64-bit numbers through the long type, we can use that. We can then import and use the function as follows:

usingSystem;usingSystem.Runtime.InteropServices;publicclassProgram{[DllImport("kernel32.dll")]staticexternboolGetSystemTimes(outlongidleTime,outlongkernelTime,outlonguserTime);publicstaticvoidMain(){longidleTime,kernelTime,userTime;GetSystemTimes(outidleTime,outkernelTime,outuserTime);Console.WriteLine("Your CPU(s) have been idle for: "+(newTimeSpan(idleTime)).ToString());Console.ReadKey();}}

Note that the use of out or ref in parameters automatically makes it a pointer to the unmanaged function.

GetProcessIoCounters

[edit | edit source]

To pass pointers to structs, we can use the out or ref keyword:

usingSystem;usingSystem.Runtime.InteropServices;publicclassProgram{structIO_COUNTERS{publiculongReadOperationCount;publiculongWriteOperationCount;publiculongOtherOperationCount;publiculongReadTransferCount;publiculongWriteTransferCount;publiculongOtherTransferCount;}[DllImport("kernel32.dll")]staticexternboolGetProcessIoCounters(IntPtrProcessHandle,outIO_COUNTERSIoCounters);publicstaticvoidMain(){IO_COUNTERScounters;GetProcessIoCounters(System.Diagnostics.Process.GetCurrentProcess().Handle,outcounters);Console.WriteLine("This process has read "+counters.ReadTransferCount.ToString("N0")+" bytes of data.");Console.ReadKey();}}
close