Getfield.SetValue不起作用 [英] Getfield.SetValue doesn't work

查看:367
本文介绍了Getfield.SetValue不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我目前的项目中,我偶然发现了这个问题:

in my project i'm currently working on i stumbled upon this problem:

我想创建"ApiID"类的实例.我从Reflector那里获得了代码,如您所见,.dll(不是我的Project)导入是来自我无法访问的完全托管代码.

I want to create a Instance of the Class "ApiID". I got the Code from Reflector, as you can see the .dll (not my Project) imports is from ummanaged code, which i don't have access to.

    [StructLayout(LayoutKind.Sequential, Size=0x10), CLSCompliant(false), NativeCppClass, DebugInfoInPDB, MiscellaneousBits(0x40)]
public struct ApiId
{
    private long <alignment member>;
    public static unsafe void <MarshalCopy>(ApiId* idPtr1, ApiId* idPtr2)
    {
        ApiId.{ctor}(idPtr1, (ApiId modopt(IsConst)* modopt(IsImplicitlyDereferenced)) idPtr2);
    }

    public static unsafe void <MarshalDestroy>(ApiId* idPtr1)
    {
        ApiId.{dtor}(idPtr1);
    }
}

我的C#代码如下:

var _apiId = new ApiId();
long vlue = 0x0000000041403070;
typeof(ApiId).GetField("<alignment member>", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(_apiId, vlue);

代码成功运行,但是该字段未更改并保持为0 ...我在做什么错? 问候

The Code Runs succesfully, but the Field does not change and stays 0... what am I doing wrong? greetings

推荐答案

这里的问题是拳击.

此行:

typeof(ApiId).GetField("<alignment member>", ...).SetValue(_apiId, vlue);

会将_apiId中的struct值装箱,并设置装箱副本的字段值.它不会改变原始的.

will box the struct value in _apiId and set the field value of the boxed copy. It will not change the original.

FieldInfo.SetValue 定义如下:

public void SetValue(
    Object obj,
    Object value
)

第一个参数,即您的_apiId将被装箱.装箱将复制struct值.因此,SetValue将更改装箱的副本,而不是原始副本.

So the first parameter, your _apiId will be boxed. Boxing will make a copy of the struct value. SetValue will thus change the boxed copy and not the original.

相反,您可以自己将对象装箱:

Instead, you can box the object yourself:

object apiId = new ApiId();
long vlue = ...
typeof(ApiId)...
_apiId = (ApiId)apiId;

这是一个演示的 .NET小提琴.尝试更改注释掉的那一行以查看区别.

Here's a .NET Fiddle that demonstrates. Try changing which line is commented out to see the difference.

这篇关于Getfield.SetValue不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆