c# 读取IntPtr 中的数据 z

c++的写法是这样的:
LRESULT CPictureQueryDlg::OnQueryPicNty(WPARAM wp, LPARAM lp)
{
EnableWindow(TRUE);

BYTE *pbyMsg = (BYTE*)lp;

// 得到当前页数目
m_dwCurCount = *reinterpret_cast<DWORD*>(pbyMsg);
// 得到总数量
m_dwTotalCount = *reinterpret_cast<DWORD*>(pbyMsg + sizeof(DWORD));

// 得到查询结果指针
TNVR_PIC_GRABTASK* ptResultQuery = reinterpret_cast<TNVR_PIC_GRABTASK*>(pbyMsg + sizeof(DWORD)*2);
memset(m_atGrTask, 0, sizeof(TNVR_PIC_GRABTASK) * NVR_MAXNUM_RECORDQUERY);
memcpy(m_atGrTask, ptResultQuery, m_dwCurCount * sizeof (TNVR_PIC_GRABTASK));
}

 

已经拿到IntPtr了的话可以用类型强制转换获取IntPtr里的东西:

(要获取的类型)Marshal.PtrToStructure(ptr,typeof(要获取的类型));
//这样就转换到你c#可以操作的数据类型然后来读取内容,
//我不知道这个在你那里能否适用,因为PtrToStructure并不是所有情况都适用,如果用这个方法的话具体可以看看MSDN

 主要是需要获得类型的长度,如果长度获得不准确,读到的数据就会有问题。
(StructureType)Marshal.PtrToStructure((IntPtr)((uint)(pbyMsg + sizeof(uint) * 2 + i * Marshal.SizeOf(typeof(StructureType)))), typeof(StructureType));

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace OpenCover.Framework.Communication
{
    public interface IMarshalWrapper
    {
        T PtrToStructure<T>(IntPtr pinnedMemory);
        void StructureToPtr<T>(T structure, IntPtr pinnedMemory, bool fDeleteOld);
    }

    public class MarshalWrapper : IMarshalWrapper
    {
        public T PtrToStructure<T>(IntPtr pinnedMemory)
        {
            return (T)Marshal.PtrToStructure(pinnedMemory, typeof(T));
        }

        public void StructureToPtr<T>(T structure, IntPtr pinnedMemory, bool fDeleteOld)
        {
            Marshal.StructureToPtr(structure, pinnedMemory, fDeleteOld);
        }
    }
}

 

posted on 2015-01-03 09:37  武胜-阿伟  阅读(17951)  评论(0编辑  收藏  举报