[英]How to use unsafe context in Unity
我想在使用 CLR 的 Unity 中使用c#
c++ code
。
該程序在統一之外正常工作,但在引擎內部它給了我一個錯誤:
“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();
}
}
}
// ...
}
您必須在Unity中明確啟用unsafe
代碼。 您可以按照以下步驟操作:
1 。 第一步,將Api兼容級別更改為.NET 2.0子集 。
2 。 在<Project Path>/Assets
目錄中創建一個文件,並將其命名為smcs.rsp,然后將-unsafe
放在該文件中。 保存並關閉該文件。
關閉並重新打開Visual Studio和Unity。 你必須重新啟動它們 。
值得一提的是這樣做的,重新開始又團結和Visual Studio,但問題仍然存在,甚至后, 重命名的smcs.rsp文件CSC.RSP,或gmcs.rsp每一次,直到你得到一個重新啟動作品。 雖然, smcs.rsp應該是第一次這樣做。
在此之后編譯的簡單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);
}
}
}
編輯:
對於最新的Unity版本,文件名應為mcs.rsp 。 其他一切都是一樣的。
更新:在 unity 2019 及以后,我們沒有 2.0 子集。 使用 2.0 標准。
盡管 mcs.rsp 有效,但有一條警告指出 mcs 已過時,我們應該改用 csc.rsp。
但它確實有效!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.