C#如何将IntPtr转换为结构? [英] c# how to convert IntPtr to struct?

查看:150
本文介绍了C#如何将IntPtr转换为结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的ATL com服务器:

A simple ATL com server:

STDMETHODIMP CMyMath::get_Version(sVersionStruct **ppVer)
{
    sVersionStruct* pVer = reinterpret_cast<sVersionStruct*>(CoTaskMemAlloc(sizeof(sVersionStruct)));
    if (!pVer) {
        return E_OUTOFMEMORY;
    } else {
        *pVer = ver_;
        *ppVer = pVer;
        return S_OK;
    }
    return S_OK;
}

STDMETHODIMP CMyMath::put_Version(sVersionStruct* ver)
{
    ver_ = *ver;
    return S_OK;
}

idl定义:

typedef 
[
    uuid(72A4AA5B-6AD0-4249-B4CB-2FFB08301608)
]
struct tagVersionStruct {
    int majorVersion;
    int minorVersion;
} sVersionStruct;

    [propget]
    HRESULT Version([out, retval, ref]sVersionStruct** ver);
    [propput]
    HRESULT Version([in]sVersionStruct* ver)

c#.net客户端:

c# .net client:

    MathServLib.sVersionStruct ver;
    ver.minorVersion = 1;
    ver.majorVersion = 3;
    math.set_Version(ver);

    ver.minorVersion = 0;
    ver.majorVersion = 0;
    IntPtr ptr = math.get_Version();
    int i = Marshal.ReadInt32(ptr); // RETURN RIGHT VALUE 3
    Marshal.PtrToStructure(ptr, ver); 

最后一行返回异常:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll. This structure is not value type.

由于 Marshal.ReadInt32(ptr)返回正确的值 3 ,为什么不能将IntPtr转换为结构?

Since Marshal.ReadInt32(ptr) could return the right value 3, why cannot convert IntPtr to struct?

PS:ILSpy的sVersionStruct:

PS: The sVersionStruct from ILSpy:

namespace MathServLib
{
    [Guid("72A4AA5B-6AD0-4249-B4CB-2FFB08301608")]
    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public struct sVersionStruct
    {
        public int majorVersion;
        public int minorVersion;
    }
}


推荐答案

您应该调用PtrToStructure的重载,该重载期望使用类型而不是对象。正是导致错误的原因:

You should call the overload of PtrToStructure that expects a type instead of an object. That's what's causing the error probably:

var ver = Marshal.PtrToStructure(ptr, typeof(MathServLib.sVersionStruct)); 

这篇关于C#如何将IntPtr转换为结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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