• C#结构体指针的定义及使用详解(intptr的用法)


    在解析C#结构体指针前,必须知道C#结构体是如何定义的。在c#中同样定义该结构体。

    C#结构体指针之C#结构体的定义:

    1. [StructLayout(LayoutKind.Sequential)]  
    2.  
    3. public struct VGAStat  
    4.  
    5. {  
    6.  
    7. public int ChannelNum;//通道数量  
    8.  
    9.  
    10. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]  
    11.  
    12. public char[] Version;//版本信息  
    13.  
    14. public uint CPUUsage;//CPU占用  
    15.  
    16. public bool WorkStatusOk; //工作状态  
    17.  
    18.  
    19. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]  
    20.  
    21. public tagCheckArg[] ChannelStatistic;//通道信息  
    22.  

    定义完结构体后,就可将接收到的C#结构体指针转换为定义的结构体对象。

    1. VGAStat entries = (VGAStat)Marshal.PtrToStructure(iptr, typeof(VGAStat));  
    2.  
    3. //iptr为接收到的非托管的结构体指针。 

    反之,也可将结构体赋值后封送到非托管内存。

    假如vga为定义后实例化并赋值了的结构体。

    1. IntPtr intptr = Marshal.AllocHGlobal(Marshal.SizeOf(vga));  
    2.  
    3. Marshal.StructureToPtr(vga, intptr, true);  
    4.  
    5. //在此发送intptr指针给目的方  
    6.  
    7. Marshal.FreeHGlobal(intptr);//释放分配的非托管内存。 

    C#结构体指针的定义及使用的相关内容那个就向你介绍到这里,希望对你了解和学习C#结构体指针有所帮助。

    将string转为IntPtr:IntPtr System.Runtime.InteropServices.Marshal.StringToCoTaskMemAuto(string)

    将IntPtr转为string:string System.Runtime.InteropServices.MarshalPtrToStringAuto(IntPtr)

    http://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices.marshal%28v=vs.110%29.aspx

  • 相关阅读:
    gitlab Failed to register this runner. Perhaps you are having network problems runner 注册失败问题解决
    gitlab pipelines 使用
    centos 7 bbr 安装
    kafka ksql && docker 安装试用
    netflix vector 系统性能监控安装使用
    keycloak && docker安装 &&spring boot 集成使用
    gogs docker 安装
    alpine docker 镜像 时区问题
    nginx 流量拷贝模块 ngx_http_mirror_module 安装试用
    ulimit  设置
  • 原文地址:https://www.cnblogs.com/zhaoxinshanwei/p/4033210.html
Copyright © 2020-2023  润新知