jakobbotsch
jakobbotsch

Reputation: 6337

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?

Upvotes: 0

Views: 1089

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283713

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."

Upvotes: 2

Related Questions