How to use unsafe code Unity

2019-02-14 06:13发布

问题:

I want to use c++ code in c# for unity using CLR.

The program works properly outside of unity, but inside of engine it gives me an error:
"cs0227: unsafe code requires the 'unsafe' command line option to be specified"

I am really confused, because the project builds successfully in visual studio (without any errors or warnings). I have "allow unsafe" button activated.

using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


public class newspawn_real : MonoBehaviour {

void Start () {

    unsafe
        {

            fixed (int * p = &bam[0, 0, 0])
            {
                CppWrapper.CppWrapperClass controlCpp = new CppWrapper.CppWrapperClass();

                controlCpp.allocate_both();
                controlCpp.fill_both();
                controlCpp.fill_wrapper();
}

回答1:

You have to explicitly enable unsafe code in Unity. You can follow the steps below:

1. First step, Change Api Compatibility Level to .NET 2.0 Subset.

2. Create a file in your <Project Path>/Assets directory and name it smcs.rsp then put -unsafe inside that file. Save and close that file.

Close and reopen Visual Studio and Unity. You must re-start both of them.

It's worth noting that even after doing this and re-starting both Unity and Visual Studio but the problem is still there, rename the smcs.rsp file to csc.rsp, or gmcs.rsp and re-start each time until you get one that works. Although, smcs.rsp should do it the first time.

Simple C# unsafe code that compiles after this.

public class newspawn_real : MonoBehaviour
{
    unsafe static void SquarePtrParam(int* p)
    {
        *p *= *p;
    }

    void Start()
    {
        unsafe
        {
            int i = 5;
            // Unsafe method: uses address-of operator (&):
            SquarePtrParam(&i);
            Debug.Log(i);
        }
    }
}

EDIT:

For the latest Unity version, the file name should be mcs.rsp. Everything else remains the-same.