I have a small C# class with a few unsafe methods. Is there a way to specify "/unsafe" option declaratively in C# source code (with #pragma or anyhow else) just for the context of the class' source file? I'd hate to create a separate assembly for such a small class, but I also really don't want the rest of the assembly (the class is currently a part of) to be enabled for unsafe code.
-
4It is not the way it works. Using the /unsafe option only suppresses a compile-time error on classes/methods that explicitly use the unsafe keyword. It doesn't make code that's not declared that way unsafe in any way.Hans Passant– Hans Passant2013-09-24 16:00:24 +00:00Commented Sep 24, 2013 at 16:00
-
So is there or not a special flag in the generated assembly, as @StriplingWarrior suggests?avo– avo2013-09-24 16:03:46 +00:00Commented Sep 24, 2013 at 16:03
2 Answers
No, this is (currently) not possible, as the entire assembly is affected by having unsafe code in it.
By including unsafe code in your assembly, you are telling the CLR that the assembly could do something, well, unsafe, which changes how the runtime acts when it loads the assembly. The biggest change here is that the CLR will simply not try to verify your unsafe code, but it also will refuse to load your assembly unless it has full-trust (e.g. you couldn't load an unsafe assembly as a normal user over click-once.)
From a technical perspective, when you use the /unsafe option, it causes the compiler to emit the IL equivalent of the following module-level attributes into your assembly:
[assembly:SecurityPermission(SkipVerification = true)]
[assembly:UnverifiableCode]
Your best option is, as you said, to isolate the unsafe code into its own separate assembly as much as possible. The fact that the assembly has only one class in it is much less of a code-smell than tainting an entire assembly full of safe code due to one unsafe class.
5 Comments
unsafe, you can also mark an entire class as unsafe. But it might be equivalent to marking all "blocks" in that class unsafe.C# has an unsafe keyword that you have to use around unsafe code, just to avoid having people using unsafe code by accident. This is as good an approach as any I can think of: If someone can introduce the unsafe keyword in a file, they could just as easily add or remove a #pragma tag or some such.
The /unsafe compiler tag tells the compiler that you're okay with people using the unsafe keyword in this assembly, and you recognize that the assembly it generates will be marked "unsafe," which may prevent it from running in less-than-Full-Trust environments. There's no way to have the compiler mark only individual classes as unsafe: people can either trust your assembly or they can't.
4 Comments
unsafe keyword to compile.Marshal class can do unsafe things "safely")RtlZeroMemory alone with a malicious IntPtr argument can do a lot more damage than my innocent pointer operations, for which I have to use "/unsafe".