代码之家  ›  专栏  ›  技术社区  ›  Thorin Oakenshield

如何在C语言中编译不安全的代码#

  •  5
  • Thorin Oakenshield  · 技术社区  · 14 年前

    我导入了一个API函数

    [DllImport("gdi32.dll")]
    private unsafe static extern bool SetDeviceGammaRamp(Int32 hdc, void* ramp);
    

    编译时显示错误

    Unsafe code may only appear if compiling with /unsafe
    

    如何编译 /unsafe . 我在用 Microsoft Visual Studio 2008

    有人能帮我找到更好的解决办法吗?

    事先谢谢。

    3 回复  |  直到 14 年前
        1
  •  13
  •   Catalin Florea    14 年前

    右键单击项目。性质。建造。检查允许不安全代码

        2
  •  3
  •   Hans Passant    14 年前

    只删除 不安全的 声明中的关键字。像这样的Windows API函数并不安全。如果笨拙的void*(托管代码中的intptr),您可以这样处理:

        private struct RAMP {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
            public UInt16[] Red;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
            public UInt16[] Green;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
            public UInt16[] Blue;
        }
    
        [DllImport("gdi32.dll")]
        private static extern bool SetDeviceGammaRamp(IntPtr hDC, ref RAMP lpRamp);
    

    还要注意,第一个参数是句柄、intptr,而不是int32。使此代码在64位操作系统上工作所必需的。

        3
  •  2
  •   Manoj Attal    13 年前

    如果有人需要,这是截图。