Unityで利用できるNativePluginの学習のため
C++で3次元座標をランダムで生成する関数を作り
Unity+C#で読み込んでC#側で数値を利用するサンプルプログラムを作成しています。
float型の一次元配列ではC++側の関数からC#側へ値を受け取り、
コンソールにて値を確認することができたので次は構造体の配列で検証してみようと思い
下記のプログラムを作成しましたが構造体の配列に値を代入した処理で上手く値を利用することができません。
何か助言をいただけないでしょうか?
C#
1using System.Collections; 2using System.Collections.Generic; 3using System.Runtime.InteropServices; 4using UnityEngine; 5 6public struct Zahyo 7{ 8 public float x; 9 public float y; 10 public float z; 11} 12 13public class NativePluginTest : MonoBehaviour { 14 15 //x,y,zに決め打ちで数値を代入する関数 16 [DllImport("NativePlugin")] private static extern void Get3DZahyo(System.IntPtr ZahyoObj, int length); 17 18 private MyPoint3D[] VerteicesList; 19 System.IntPtr Point3DPtr = System.IntPtr.Zero; 20 21 void Start () { 22 Get3DZahyoData(); 23 } 24 25 void GetPOINT3DData() 26 { 27 int num = 10; 28 VerteicesList = new Zahyo[num]; 29 for (int i = 0; i < VerteicesList.Length; i++) 30 { 31 VerteicesList[i] = new Zahyo(); 32 } 33 int _size = Marshal.SizeOf(VerteicesList[0]) * num;// array.Length; 34 35 Point3DPtr = Marshal.AllocHGlobal(_size); 36 37 Point3DPtr = Marshal.AllocCoTaskMem(_size); 38 Marshal.StructureToPtr(VerteicesList, Point3DPtr, false); 39 Get3DZahyo(Point3DPtr, num); 40 41 //ここでポインタからZahyo型の配列に値をコピーしているつもり 42 Marshal.PtrToStructure(Point3DPtr, VerteicesList); 43 44 for (int i = 0; i < VerteicesList.Length; i++) 45 { 46 //ここでUnityのコンソールに値を表示、X/Y/Zともにすべて 0 となっています。 47 Debug.unityLogger.Log("id:" + i + " x:" + VerteicesList[i].x + " y:" + VerteicesList[i].y + " z:" + VerteicesList[i].z); 48 } 49 50 Marshal.DestroyStructure(Point3DPtr, typeof(Zahyo)); 51 Marshal.FreeCoTaskMem(Point3DPtr); 52 53 } 54} 55
C++
1extern "C" 2{ 3 typedef struct _zahyo{ 4 float x; 5 float y; 6 float z; 7 }zahyo; 8 9 __declspec(dllexport) void Get3DZahyo(zahyo*dst, int length); 10 { 11 int count = 0; 12 for (int i = 0; i < length ; i++) { 13 14 dst->x = 0.1 * (i+1) ; 15 dst->y = 0.2 * (i+1); 16 dst->z = 0.3 * (i+1); 17 dst++; 18 19 count++; 20 } 21 } 22}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/20 01:52