zoukankan      html  css  js  c++  java
  • IntPtr

     IntPtr

    一:什么是IntPtr   

    先来看看MSDN上说的:用于表示指针或句柄的平台特定类型。这个其实说出了这样两个事实,IntPtr 可以用来表示指针或句柄、它是一个平台特定类型。对于它的解释,这个哥们写的比较好:It's a class that wraps a pointer that is used when calling Windows API functions. The underlying pointer may be 32 bit or 64 bit, depending on the platform

    二:用在什么地方 

    (1)C#调用WIN32 API时  
    (2)C#调用C/C++写的DLL时(其实和1相同,只是这个一般是我们在和他人合作开发时经常用到)

    三:怎样用

    例如有一函数原型定义为:DLLDemo_API int _stdcall Inprt_Test(LONG param1,HWND hWnd);那么我们在c#中引用时就要这样写:

    [DllImport("DllPlayer.dll",EntryPoint = "IP TPS OpenSteam")]

    public static extern int Inptr_Test(int param1,InPtr hWnd);

    在调用的时候就可以向Inptr_Test的第二个参数传入某一控件的Handle。这里涉及到c#类型与c++类型的对应关系,网上这种有很多,这里就不在赘述,只谈几个经常用到的和经常出错的。

    (1)一般对于char*,void*这种可以直接对应InPtr,比如在c#中,我们经常用string类型,其转化为Inptr再传给char*,void*等,转换方法为

    string txt = “test”;Marshal.StringToCoTaskMemAuto(txt);

    这里有时会用StringToCoTaskMemAnsi,不过StringToCoTaskMemAuto自动分配内存就可以了,这样会将txt的内容复制到非托管的内存块中。

    (2)对于结构体,比如有一结构体StructText,将其转换为InPtr,尽量不要直接用Marshal.StructureToPtr,这样很容易出错,可以这样来用:

    int size = Marshal.SizeOf(sTRUCText);//获取结构体占用控件大小

    IntPtr intptr = Marshal.AllocHGlobal(size);  //声明一个同样大小的空间

    Marshal.StructureToPtr(StructText,inptr,true);//将结构体放到这个空间中

  • 相关阅读:
    oracle常规操作
    shell 的算数运算
    sed 命令小结
    swing
    索引失效
    poj--1258--Agri-Net(最小生成树)
    CodeForces--626C--Block Towers (二分)
    Codeforces--629A--Far Relative’s Birthday Cake(暴力模拟)
    Codeforces--629B--Far Relative’s Problem(模拟)
    hdoj--5104--Primes Problem(素数打表)
  • 原文地址:https://www.cnblogs.com/linweimu/p/11146000.html
Copyright © 2011-2022 走看看