"unsafe code may only appear if compiling with /unsafe"

11.7k views Asked by At

I have a web application and in one of the classes the following is defined (partial):

public class DllFunction
{
    [DllImport("CARSDBI.dll", EntryPoint="CARSDBI_EnableLogging")]
    public static extern unsafe void CARSDBI_EnableLogging(int bSetting);
    ....
}

I get the "unsafe code may only appear if compiling with /unsafe" error. Searching for this error message seems to show one solution: to check "Allow unsafe code" on the Project Properties page, in the Build tab.

However, when I right-click on the project and select Properties and then Build option I don't see this checkbox, all I see is:

a drop down list "Before running startup page" with "Build web site" selected, target framework with ".NET Framework 3.5" selected and Build Solution Action with "Build web site as part of solution" checked.

1

There are 1 answers

2
Sonu Rajpoot On

This error occurs when you use unsafe keyword in your code.

Solution You can easily fixed this issue, follow the following.

Right Click on your project --> go to properties then Choose Build option and then check Allow Unsafe Code.

Actually i was facing same issue in below code, so i did that

struct Point
{
    public int x, y;
}

class MainClass12
{
    unsafe static void Main()
    {
      Point pt = new Point();
      Point* pp = &pt;
      pp->x = 123;
      pp->y = 456;
      Console.WriteLine("{0} {1}", pt.x, pt.y);
    }
}