This example shows how to define a managed struct, and pass it as an argument to the GetSystemInfo routine in the Win32 API. GetSystemInfo fills in the struct and returns that information to the managed caller.
[Note that this example is particularly simple: each field in the managed struct is a simple 2-byte or 4-byte ‘number’ that matches what the unmanaged code in GetSystemInfo expects to see. More complex examples define structs where the field sizes do not match: for example, a managed BOOLEAN (1-byte) corresponding to an unmanaged C int (4-byte)]
The example includes typedefs for the WORD, DWORD, UINT and LPVOID types found so often in the Win32 API. This is not necessary (for example, we could have simply used “unsigned short” everywhere instead of WORD) but it makes the code look more familiar to Win32 users.
#import <mscorlib.dll> typedef unsigned short WORD; typedef unsigned long DWORD; typedef unsigned int UINT; typedef void *LPVOID; [managed] struct SYSTEM_INFO { DWORD dwOemId; DWORD dwPageSize; LPVOID lpMinimumApplicationAddress; LPVOID lpMaximumApplicationAddress; DWORD dwActiveProcessorMask; DWORD dwNumberOfProcessors; DWORD dwProcessorType; DWORD dwAllocationGranularity; WORD wProcessorLevel; WORD wProcessorRevision; }; [sysimport(dll="kernel32")] extern "C" void GetSystemInfo(SYSTEM_INFO* pSI); int main(void) { SYSTEM_INFO* pSI = new SYSTEM_INFO; GetSystemInfo(pSI); Console::Write(L"The number of CPUs: "); Console::WriteLine((long)pSI->dwNumberOfProcessors); return 0; }