Trillian
Trillian

Reputation: 6437

.NET 4 method security exception when pinvoking

I've got some code which pinvokes native win32. Since I upgraded to .NET 4, the code started throwing a MethodAccessException saying:

Attempt by security transparent method 'Tek.Audio.Midi.MidiDevice.GetDevices()' to call native code through method 'Tek.Native.Windows.Multimedia.midiInGetNumDevs()' failed. Methods must be security critical or security safe-critical to call native code.

Here's what's going on:

The only security-related attributes on classes, methods and assemblies involved are AllowPartiallyTrustedCallers on library1, and I don't even know why.

It shames me to admit that I'm quite ignorant about security in .NET. What should I do to prevent this exception? And while I'm here, any good articles to get me started on .NET security?

Upvotes: 9

Views: 5991

Answers (1)

Nick Daniels
Nick Daniels

Reputation: 922

You have choices. The easiest thing to do would be to "opt-out" of the new security model.

<configuration>
  <runtime>
    <NetFx40_LegacySecurityPolicy enabled="true" />
  </runtime>
</configuration>

OR (bearing in mind I am no .Net 4 security expert)

Edit: Opting out of the .Net 4 security model is unreliable and should be avoided

You could mark your method:

[SecuritySafeCritical]

since you can use that with code designed for partially trusted callers.

Sadly I don't have a good article I can send you, I have had to figure this out like you have, by fixing my broken code. :)

Upvotes: 16

Related Questions