使用 Reflection.Emit 调用私有构造函数?
我正在尝试发出以下 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);
我绑定的委托具有签名
void* TestDelegate(IntPtr ptr)
它抛出异常
该操作可能会破坏稳定 运行时。
任何人都知道出了什么问题吗?
编辑: 好吧,我现在让 IL 开始工作了。这样做的全部目标是能够调用私有构造函数。私有构造函数需要一个指针,所以我不能使用正常的反射。现在..当我调用它时,我得到一个例外:
尝试方法
到 访问方法<私有构造函数> 失败。
显然它正在执行安全检查 - 但根据经验,我知道反射能够正常执行这样的私有操作,所以希望有一种方法可以禁用该检查?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常 arg-0 是
this
指针,而不是参数列表中的IntPtr
。编辑:要回答您的新问题,您需要使用其他
DynamicMethod
构造函数之一。例如,DynamicMethod 构造函数(String、Type、Type[]、Type )
被描述为“与类型逻辑关联。这种关联使其能够访问该类型的私有成员。”Usually arg-0 is the
this
pointer, not theIntPtr
in your parameter list.EDIT: To answer your new question, you need to use one of the other
DynamicMethod
constructors. For example, theDynamicMethod 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."