zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }
    
  • 相关阅读:
    python初级 0 出发吧
    10 个免费的服务器监控工具推荐
    Nginx 的线程池与性能剖析
    Java中 Comparator接口 与Comparable 的区别
    ORACLE分区表、分区索引详解
    搜索引擎爬虫蜘蛛的USERAGENT大全
    ios和android的发展前景比较
    DES、3DES、AES加密方式
    jsp、freemarker、velocity区别详解
    面向对象五大原则(SRP、OCP、LSP、DIP、ISP)
  • 原文地址:https://www.cnblogs.com/zeroone/p/4199141.html
Copyright © 2011-2022 走看看