【问题标题】:How to get integer value from IntPtr-parameter in managed delegate that is called from native function with void *?如何从使用 void * 的本机函数调用的托管委托中的 IntPtr 参数获取整数值?
【发布时间】:2016-06-23 09:59:07
【问题描述】:

我有本机功能

void SetValue(char *FieldName, void *pValue);

我想将其更改为调用较早的 set callback/delegate

有签名

void SetValueDelegate(string fieldName, IntPtr value);

我这样调用原生 SetValue:

int IntValue = 0;
SetValue("MyField", &IntValue);

现在我认为我可以将其转换为托管委托:

void SetValueDelegate(string fieldName, IntPtr value)
{
    if (fieldName == "MyField")
    {
        int intValue = (int)value;
    }
}

这不起作用。如果转换为 long,则值为 204790096。

这应该怎么做?

【问题讨论】:

    标签: c# pinvoke managed


    【解决方案1】:

    在您的托管代码中,valueint 变量的地址。因此,您可以像这样读取该变量:

    int intValue = Marshal.ReadInt32(value);
    

    您的代码只是读取地址,而不是存储在该地址的值。

    【讨论】:

    • 谢谢!这自然是正确的。我找到了另一种方式: (int)Marshal.PtrToStructure(value, typeof(int));但你的答案更清楚。
    • 这也可以,但我想ReadInt32 避免了装箱和拆箱步骤。
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2016-09-15
    • 2013-06-28
    • 2014-08-18
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多