tags:

views:

24

answers:

1

This rule indicates that P/Invokes should not be made public. My question is why? A caller can trivially create their own declaration within their own assembly to make the exact same call. A caller could just write a C library to call the API. What benefit, security or otherwise, is gained by making these declarations internal?

+2  A: 

Well, in the .NET security model, it's possible for your assembly to have permission to do P/Invokes, but for your caller not to have. (AllowPartiallyTrustedCallersAttribute, which permits code running as partially trusted to call into an assembly that is fully trusted, exists to enable this.)

Which is, essentially, what you want when the library you are writing exists to provide safe access, or limited access, to some system facility that you don't want sandboxed applications of one type or another to have arbitrary access to.

On another note, it's politeness as well as security. P/Invokes are de facto unsafe, inasmuch as calling them badly can result in all kinds of interesting ways to crash that you generally don't run into in the comfortable .NET world. Wrapping some error-checking and general safety code around them, along with such things as mangling input data into the Win32 API (or whatever's) format, translating its error codes into the appropriate .NET exceptions, etc., etc., is just plain courtesy to your library's future users, IMO.

Cerebrate
Thanks. Your description of the .NET security model clears things up for me.
anvilis
I'd vote for this, but I'm new and don't have the required reputation.
anvilis
@anvilis: You can accept their answer, though - which will help ;)
Reed Copsey