对非托管代码的调用
跨平台调用 – 过程
l 声明方法的输出
l
l
l 添加 DLLImportAttribute
Ø
Ø
l 调用包装 (wrapper)
private static extern int PlaySound(
string file, IntPtr hModule, int flags);
[DllImport("coredll.dll")]
private static extern int PlaySound(
string file, IntPtr hModule, int flags);
PlaySound(“Windows\someSound.wav”,
IntPtr.Zero,SND_FILENAME);

| The process for working with Platform Invoke is relatively straightforward. The hardest part is the first step, which involves defining a managed function that maps to the desired function in the unmanaged DLL. The difficult part here is ensuring that you use the appropriate managed data types for your parameters. The Compact Framework SDK provides a reference mapping common unmanaged typed to their managed counterparts. The example here declares a method named PlaySound that takes three parameters. Notice that the method is marked as “extern” or “external”. This instructs the runtime that it needs to go out and find the body of the function in another binary.
| The DLLImportAttribute instructs the runtime about where to find the function, and optionally, how to marshal data to and from the unmanaged function. Here, we are indicating that the PlaySound function can be found in the coredll DLL. This is one of the many Pocket PC OS APIs.
| Finally, you can write code that calls the managed wrapper just like any other managed function call. Here, we make a call to the PlaySound method and pass in a path to the someSound wave file.
| When this executes, the runtime will intercept the call the PlaySound, locate the coredll DLL, locate the PlaySound function in that DLL, and call the function, marshalling the parameters and return value as appropriate.