zoukankan      html  css  js  c++  java
  • C# call Win32 api时,-1如何转换为DWORD

    当使用(uint)-1时,编译器会给出警告:常量-1无法转换为uint,使用unchecked语句重写。DWORD在转换为C#类型时为uint,既然无法使用uint强制转型(-1),那就需要其他办法了。既然编译器给出的提示是使用unchecked语句重写,可以一试。之前没有使用过unchecked语句,所以不熟悉其用法。看了下参考文档,MSDN是这样描述unchecked的:

    The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.
    In an unchecked context, if an expression produces a value that is outside the range of the destination type, the overflow is not flagged. For example, 
    because the calculation in the following example is performed in an unchecked block or expression, the fact that the result is too large for an integer
    is ignored, and int1 is assigned the value -2,147,483,639.

    简单翻译一下,其意思是:

    unchecked 关键字用于禁止编译器对整型算术运算和转型进行溢出检查。
    在unchecked上下中,如果一个表达式产生的值超过了目标类型的值范围,那么这个溢出不会被标记报告。举一个例子,在接下来的例子中演示了一个unchecked块,计算的结果已经超过了整型的最大值......
    (就是MAX INT + 10, 结果超过了最大的整型能表达的值。在计算机中,溢出会造成符号位进位或者取反)

    所以当遇到Win32 Api中这样的函数定义以及参数说明时,可以使用unchecked 来传入 -1 .

    //dwPrefMaxLen [in]
    //A value that specifies the preferred maximum length of returned data, in //8-bit bytes. If this parameter is -1, the buffer that is returned is large //enough to hold all available data.
    
    uint preMax;
    unchecked
    {
        preMax = (uint)-1;
    }

    参考:

    [1]unchecked, https://msdn.microsoft.com/en-us/library/a569z7k8.aspx

  • 相关阅读:
    转载:linux or unit 连接 windows的远程桌面-rdesktop(略有修改)
    Excel技巧
    Linux实用配置(ubuntu)
    转载:VMware linux 虚拟机中修改MAC地址
    windows技巧
    cdoj1099
    hdu1160(问题)
    c#学习笔记
    hdu1176
    qsort(),sort() scanf();
  • 原文地址:https://www.cnblogs.com/jjseen/p/5930292.html
Copyright © 2011-2022 走看看