Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 284
Thorin Oakenshield Avatar asked Oct 25 '10 10:10

Thorin Oakenshield


3 Answers

right click on project. properties. build. check allow unsafe code

like image 76
Catalin Florea Avatar answered Oct 04 '22 17:10

Catalin Florea


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.

like image 31
Hans Passant Avatar answered Oct 04 '22 16:10

Hans Passant


Here is the screenshot if someone needs.

UnsafeCodeImage

like image 36
Manoj Attal Avatar answered Oct 04 '22 16:10

Manoj Attal