问题描述
我想在C#中使用C ++代码来统一使用CLR.
I want to use c++ code in c# for unity using CLR.
我真的很困惑,因为该项目在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兼容性级别更改为 .NET 2.0子集.
1. First step, Change Api Compatibility Level to .NET 2.0 Subset.
2 .在您的<Project Path>/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,但问题仍然存在,将 smcs.rsp 文件重命名为 csc.rsp 或 gmcs.rsp ,然后每次重新启动直到你得到一个可行的.虽然, smcs.rsp 应该是第一次.
It's worth noting that even after doing this and re-starting both Unity and Visual Studio but the problem is still there, rename the smcs.rsp file to csc.rsp, or gmcs.rsp and re-start each time until you get one that works. Although, smcs.rsp should do it the first time.
此后编译的简单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版本,文件名应为 mcs.rsp .其他所有内容都保持不变.
For the latest Unity version, the file name should be mcs.rsp. Everything else remains the-same.
这篇关于如何使用不安全的代码Unity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!