简体   繁体   English

用Reflection.Emit调用私有构造函数?

[英]Calling private constructors with Reflection.Emit?

I'm trying to emit the following IL: 我正在尝试发出以下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. 编辑:好的,所以我现在让IL工作了。 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? 显然它正在执行安全检查 - 但根据经验,我知道Reflection能够正常地执行这样的私有事情,所以希望有一种方法可以禁用该检查吗?

Usually arg-0 is the this pointer, not the IntPtr in your parameter list. 通常arg-0是this指针,而不是参数列表中的IntPtr

EDIT: To answer your new question, you need to use one of the other DynamicMethod constructors. 编辑:要回答您的新问题,您需要使用其他DynamicMethod构造函数之一。 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." 例如, DynamicMethod Constructor (String, Type, Type[], Type)被描述为“在逻辑上与类型相关联。这种关联使它可以访问该类型的私有成员”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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