Thursday, September 16, 2004

Performance: Calling Unmanaged Code

-- PInvoke is a fast way to invoke unmanaged code

-- The CLR does expensive CAS security stack walks on every call into that method to insure that all callers have unmanaged code access permissions. For non-security sensitive scenarios, disable the security check for better performance.
// Use only when security is not a major concern
[DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity]
public static extern bool Beep(int frequency, int duration);

*TLBIMP generates interop assemblies
*Disable the CAS stack-walks that by building interop assemblies with the TLBIMP /unsafe switch
*Forces TLBIMP to generate code that create RCWs that perform link demands rather than full demands
*Use with caution! Can open the door to luring attacks

C:\>tlbimp mycomponent.dll /out:UnSafe_MyComponent.dll /unsafe

No comments: