如何在Unity中使用不安全上下文

问题描述 投票:0回答:3

我想在使用 CLR 的 Unity 中使用

c++ code
中的
c#

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

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

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();
            }
        }
    }
    // ...
}
c# c++ unity-game-engine clr unsafe
3个回答
39
投票

您必须在 Unity 中显式启用

unsafe
代码。您可以按照以下步骤操作:

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

2。在您的

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

  • 关闭并重新打开 Visual Studio 和 Unity 编辑器。
  • 您必须重新启动它们

值得注意的是,即使执行此操作并重新启动 Unity 和 Visual Studio 后,如果问题仍然存在,

  • smcs.rsp
    文件重命名为
    csc.rsp
    gmcs.rsp
    mcs.rsp

每次重新启动 Unity 编辑器和 Visual Studio,直到获得可以运行的版本。有关要使用的文件名的更多详细信息,请参阅平台相关编译文档

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

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

6
投票

更新: 在 Unity 2019 及以后版本中,我们没有 2.0 子集。 使用2.0标准。

虽然 mcs.rsp 可以工作,但有一个警告指出 mcs 已过时,我们应该使用 csc.rsp 代替。

但它确实有效!


0
投票

请注意,您收到的错误可能会产生误导:

Assets\Foo\Foo.cs(832,13):错误CS0227:不安全的代码可能 仅在使用 /unsafe 编译时出现。启用“允许‘不安全’代码” “Assets/Game.asmdef”检查器修复此错误。

尽管 Foo.cs 位于 Assets\Foo\Foo.asmdef 中,而这显然是需要设置开关的。

© www.soinside.com 2019 - 2024. All rights reserved.