简体   繁体   中英

Calling private constructors with Reflection.Emit?

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?

Usually arg-0 is the this pointer, not the IntPtr in your parameter list.

EDIT: To answer your new question, you need to use one of the other DynamicMethod constructors. For example, the DynamicMethod Constructor (String, Type, Type[], Type) is described as "logically associated with a type. This association gives it access to the private members of that type."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM