如何使用不安全的代码Unity [英] How to use unsafe code Unity

查看:635
本文介绍了如何使用不安全的代码Unity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C#中使用C ++代码来统一使用CLR.

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

程序在统一之外可以正常运行,但是在引擎内部却给我一个错误:
"cs0227:不安全代码要求指定'unsafe'命令行选项"

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"

我真的很困惑,因为该项目在Visual Studio中成功构建(没有任何错误或警告).我已激活"允许 不安全"按钮.

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();
}

推荐答案

您必须在Unity中显式启用unsafe代码.您可以按照以下步骤操作:

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

1 .第一步,将 Api兼容性级别更改为 .NET 2.0子集.

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

2 .在您的<Project Path>/Assets目录中创建一个文件,并将其命名为 smcs.rsp ,然后将-unsafe放入该文件中.保存并关闭该文件.

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.

关闭并重新打开Visual Studio和Unity. 您必须重新启动它们.

值得注意的是,即使这样做并重新启动Unity和Visual Studio,但问题仍然存在, smcs.rsp 文件重命名为 csc.rsp gmcs.rsp ,然后每次重新启动直到你得到一个可行的.虽然, smcs.rsp 应该是第一次.

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.

此后编译的简单C#不安全代码.

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);
        }
    }
}

对于最新的Unity版本,文件名应为 mcs.rsp .其他所有内容都保持不变.

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

这篇关于如何使用不安全的代码Unity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆