2016-08-24 8 views
3

私はCLRを使用して単一性のためにc#でC++コードを使用したいと思います。安全でないコードを使用する方法Unity

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"

私は本当に混乱しています。なぜなら、プロジェクトはビジュアルスタジオ(エラーや警告なし)で正常に構築されるからです。私は "安全でない"ボタンを有効にしました。

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(); 
} 
+0

不明な点がある場合は教えてください。 –

+1

Unityはブラックボックスなので、コード変換時にどのC#機能がサポートされているのか分かりません。大まかな推測は危険なものではありません。 'Marshal'クラスメソッドの使用を検討しましたか? – Aybe

+0

dllインポートを意味しますか? '[DllImport( "C++ unitshi.dll")]' static extern int add(int a、int b); ' –

答えて

9

Unityでunsafeコードを明示的に有効にする必要があります。次の手順を実行できます。

最初のステップ、変更API互換性レベル.NET 2.0サブセット

enter image description here

<Project Path>/Assetsディレクトリにファイルを作成し、という名前のsmcs.rspと入力し、-unsafeをそのファイルに入れます。そのファイルを保存して閉じます。

enter image description here

を閉じると、Visual Studioとユニティを再開。の両方を再起動する必要があります。

それがあってもこれを行うと、再起動後にUnityおよびVisual Studioの両方は注目に値しますが、問題はまだそこにある、renamesmcs.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); 
     } 
    } 
} 

EDIT:最新Unityバージョンについては

、ファイル名がmcs.rspでなければなりません。他のすべては同じままです。

+1

ありがとうございます!これは地球上で最高のフォーラムです。 –

関連する問題