I'm looking for a way to filter out methods which have the unsafe
modifier via reflection. It doesn't seem to be a method attribute.
Is there a way?
EDIT: it seems that this info is not in the metadata, at least I can't see it in the IL. However reflector shows the unsafe
modifier in C# view. Any ideas on how it's don开发者_StackOverflow中文版e?
EDIT 2: For my needs I ended up with a check, that assumes that if one of the method's parameters is a pointer, or a return type is a pointer, then the method is unsafe.
public static bool IsUnsafe(this MethodInfo methodInfo)
{
if (HasUnsafeParameters(methodInfo))
{
return true;
}
return methodInfo.ReturnType.IsPointer;
}
private static bool HasUnsafeParameters(MethodBase methodBase)
{
var parameters = methodBase.GetParameters();
bool hasUnsafe = parameters.Any(p => p.ParameterType.IsPointer);
return hasUnsafe;
}
This doesn't handle, of course, a situation where an unsafe block is executed within a method, but again, all I am interested in is the method signature.
Thanks!
Unfortunately the unsafe keyword simply wraps the body of the method in an unsafe block and doesn't emit anything that reflection would see. The only way to be certain is to disassemble the method and see if there are any unsafe operations inside.
That's the job of an IL verifier. PEVerify.exe in the Windows SDK's bin directory. It verifies the IL in the method bodies and flags unsafe IL. Pointers, mostly. You'll get a fairly big list if you let it loose on the system.dll assembly.
Note that it refuses to verify mscorlib.dll, you're pretty stuck if that's the one you care about. Copying and renaming it doesn't help.
Don't think there is a way out of the box. If the code you're reflecting is yours, you can create your own UnsafeAttribute
and tag those methods with the attribute and filter on that...
精彩评论