Calling private constructors with Reflection.Emit?

Posted by Jakob Botsch Nielsen on Stack Overflow See other posts from Stack Overflow or by Jakob Botsch Nielsen
Published on 2010-12-24T22:34:25Z Indexed on 2010/12/25 0:54 UTC
Read the original article Hit count: 234

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about cil