Calling private constructors with Reflection.Emit?
- by Jakob Botsch Nielsen
I'm trying to emit the following IL:
LocalBuilder pointer = il.DeclareLocal(typeof(IntPtr));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Stloc, pointer);
il.Emit(OpCodes.Ldloca, pointer);
il.Emit(OpCodes.Call, typeof(IntPtr).GetMethod("ToPointer"));
il.Emit(OpCodes.Ret);
The delegate I bind with has the signature
void* TestDelegate(IntPtr ptr)
It throws the exception
Operation could destabilize the
runtime.
Anyone knows what's wrong?
EDIT:
Alright, so I got the IL working now. The entire goal of this was to be able to call a private constructor. The private constructor takes a pointer so I can't use normal reflection. Now.. When I call it, I get an exception saying
Attempt by method <built method> to
access method <private constructor>
failed.
Apparently it's performing security checks - but from experience I know that Reflection is able to do private stuff like this normally, so hopefully there is a way to disable that check?