Finally, a word about the performance of Platform Invoke. Each individual Platform Invoke call has an overhead of between 10 and 30 x86 instructions. In addition to this, extra costs will be incurred if parameter data has to be marshaled. There is no marshaling cost between blittable types that have the same representation in managed and unmanaged code (for example, a C++ int and a System.Int32 ), but there might be significant cost involved when marshaling other types, such as strings and arrays.
You will get better performance if you have as few Platform Invoke calls as possible, and if these calls marshal as much data as possible.
If you know that there is no possibility that the unmanaged routines you are calling could perform any damaging operations, you can switch off the runtime security checks by using the SuppressUnmanagedCodeSecurity attribute. Under normal circumstances, calls into unmanaged code cause a security check to ensure that every routine in the call chain has UnmanagedCode permission. This obviously imposes an overhead on the call, and can be switched off using SuppressUnmanagedCodeSecurity . Using this attribute places the burden of security back onto the programmer, and of course, you'll only ever want to use it if you find that security checking is adding unacceptable overheads.
//Suppresssecuritychecking [DllImport("MyDll.dll",CharSet=CharSet.Auto), SuppressUnmanagedCodeSecurity] publicstaticexternvoidSomeFunction();
As a final performance tip, note that it is possible to load DLLs and locate routines before any Platform Invoke calls are made. Normally the Platform Invoke prototype is evaluated, DLLs are loaded, and routines located on the first call to a routine. The System::Runtime::InteropServices::Marshal class contains two methods that let you preload DLLs for use with Platform Invoke methods : Prelink and PrelinkAll . The Prelink method takes a MethodInfo object that describes the method to be invoked by Platform Invoke, and then verifies the Platform Invoke prototype, loads the DLL, and verifies that it contains the requested method. PrelinkAll is similar, in that it calls Prelink for all the methods on a given class.