views:

247

answers:

2

When using P/Invoke, adding [SuppressUnmanagedCodeSecurity] can speed calls from managed code into unmanaged code in trusted scenarios.

Is there a way to accomplish the same thing in the reverse direction, to speed things up when I call from unmanaged code back into managed code? Profiling shows a much higher overhead going in that direction in our application.

+1  A: 

I haven't found anything about suppressing code security, maybe because there's no such stack-walking checks calling from the unmanaged side, but how you marshal your types has an effect on performance. Here's a link showing different ways of marshaling strings, and the perf results: http://blogs.msdn.com/junfeng/archive/2007/07/09/reverse-p-invoke-marshaling-performance.aspx

omellet
A: 

I don't believe that there's any such security check from unmanaged into managed.

You can see the security checks counted as they occur if you go to Process Explorer. Find your process, click on Properties, Go to the .NET tab and select ".NET CLR Security" from the drop down.

I wrote a simple test app that just calls into unmanaged code, passing a delegate and then the unmanaged code calls that delegate immediately. There was a security check counted for each call in my test loop.

Then I added [SuppressUnmanagedCodeSecurityAttribute()] to the Managed ---> Unmanaged call and the security checks went to 0.

Michael Covelli
But I'm having a similar issue with callback speed so let me know if you've learned anything helpful.
Michael Covelli