【问题标题】:How to use unsafe context in Unity如何在 Unity 中使用不安全的上下文
【发布时间】:2017-01-01 02:33:31
【问题描述】:

我想使用 CLR 将 c++ code 中的 c# 用于 Unity。

该程序在 unity 之外正常工作,但在引擎内部却给我一个错误:
“cs0227: unsafe code requires the 'unsafe' command line option to be specified”

我真的很困惑,因为该项目在 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();
            }
        }
    }
    // ...
}

【问题讨论】:

  • 如果有什么不清楚的地方请告诉我,我会改正的。
  • 由于 Unity 是一个黑盒,我们并不真正知道在转换代码时支持哪些 C# 功能。粗略的猜测是不安全的东西不是。您是否考虑过使用Marshal 类方法?
  • 你的意思是dll导入吗? ' [DllImport("C++ unitshi.dll")] ' static extern int add(int a, int b);'
  • 不,我的意思是所有指针类型和指针算法,他们当然必须为网络播放器画一条线。但似乎@Programmer 的答案允许你这样做。

标签: c# c++ unity3d clr unsafe


【解决方案1】:

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

1。第一步,将Api Compatibility Level改为.NET 2.0 Subset

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

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

值得注意的是,即使在这样做并重新启动 Unity 和 Visual Studio 之后,如果问题仍然存在,

  • smcs.rsp 文件重命名为csc.rspgmcs.rspmcs.rsp

每次都重新启动 Unity 编辑器和 Visual Studio,直到你得到一个可以工作的。有关要使用的文件名的更多详细信息,请参阅Platform Dependent Compilation documentation

在此之后编译的简单 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);
        }
    }
}

【讨论】:

  • 非常感谢!这是世界上最好的论坛。
  • 值得注意的是,我们应该使用 smcs.rsp (for .Net 2.0 Subset) 或 gmcs.rsp (for .Net 2.0)
【解决方案2】:

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

虽然 mcs.rsp 有效,但有一个警告指出 mcs 已过时,我们应该改用 csc.rsp。

但它确实有效!

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    相关资源
    最近更新 更多