gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:52 29 4
gpt4 key购买 nike

我想在 c# 中为使用 CLR 的 Unity 使用 c++ 代码

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 中成功构建(没有任何错误或警告)。我激活了“允许 不安全”按钮。

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

最佳答案

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

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

API Compatibility level

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

create smcs.rsp file

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

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

  • 重命名 smcs.rsp归档到csc.rsp , gmcs.rspmcs.rsp

每次都重新启动 Unity Editor 和 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);
}
}
}

关于c# - 如何在 Unity 中使用不安全上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39132079/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com