如何在 Unity 中使用不安全的上下文 [英] How to use unsafe context in Unity

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

问题描述

我想在 c# 中使用 c++ 代码 for Unity 使用 CLR.​​

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

程序在 unity 之外正常工作,但在引擎内部它给了我一个错误:
cs0227:不安全代码需要指定不安全"命令行选项"

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 Compatibility Level 更改为 .NET 2.0 Subset.

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

2.在您的 /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 后,如果问题仍然存在,

It's worth noting that even after doing this and restarting both Unity and Visual Studio, if the problem is still there,

  • smcs.rsp 文件重命名为 csc.rspgmcs.rspmcs.rsp
  • Rename the smcs.rsp file to csc.rsp, gmcs.rsp or mcs.rsp

每次都重新启动 Unity Editor 和 Visual Studio,直到您得到一个可以工作的.有关要使用的文件名的更多详细信息,请参阅平台相关编译文档.

Restart Unity Editor and Visual Studio each time until you get one that works. For more details about the file name to use, refer to Platform Dependent Compilation documentation.

在此之后编译的简单 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 中使用不安全的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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