How to compile Unsafe code in C#
I've imported an API function like
[DllImport("gdi32.dll")]
private unsafe static extern bool SetDeviceGammaRamp(Int32 hdc, void* ramp);
while compiling its showing开发者_运维知识库 an error like
Unsafe code may only appear if compiling with /unsafe
how to compile with /unsafe
. i'm using Microsoft Visual Studio 2008
can any one help me with a better solution.
Thanks in advance.
right click on project. properties. build. check allow unsafe code
Just delete the unsafe keyword from the declaration. Windows API functions like this are not unsafe. You can get rid if the awkward void* (IntPtr in managed code) like this:
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);
Also note that the first argument is a handle, an IntPtr, not an Int32. Required to make this code work on 64-bit operating systems.
Here is the screenshot if someone needs.
精彩评论