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

发布于 2024-10-08 19:31:37 字数 720 浏览 0 评论 0原文

我正在尝试发出以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜司空 2024-10-15 19:31:37

通常 arg-0 是 this 指针,而不是参数列表中的 IntPtr

编辑:要回答您的新问题,您需要使用其他 DynamicMethod 构造函数之一。例如,DynamicMethod 构造函数(String、Type、Type[]、Type ) 被描述为“与类型逻辑关联。这种关联使其能够访问该类型的私有成员。”

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文