Last active
February 23, 2025 15:52
-
-
Save baobao/f0766c96bf15a326379d00b6be8ab88d to your computer and use it in GitHub Desktop.
C#/C++間構造体データ送信サンプル http://shibuya24.info/entry/unity-cs-cpp-struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C#からC++に構造体を送るサンプル(C#側処理) | |
using System; | |
using System.Runtime.InteropServices; | |
public static class SendStructCsToCpp | |
{ | |
[DllImport("TestDll.dll", CallingConvention = CallingConvention.Cdecl)] | |
static extern void SendStruct(ref StructData output, IntPtr input); | |
public struct StructData | |
{ | |
public int id; | |
public float value; | |
} | |
static void Main() | |
{ | |
var inputData = new StructData() | |
{ | |
id = 10, | |
value = 0.5f | |
}; | |
var memorySize = Marshal.SizeOf(typeof(StructData)); | |
// アンマネージド構造体のメモリ確保 | |
System.IntPtr inputPtr = Marshal.AllocCoTaskMem(memorySize); | |
// マネージド構造体をアンマネージドにコピーする | |
Marshal.StructureToPtr(inputData, inputPtr, false); | |
// C++から戻す結果構造体 | |
var result = new StructData(); | |
SendStruct(ref result, inputPtr); | |
// アンマネージドのメモリを解放 | |
Marshal.FreeCoTaskMem(inputPtr); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C#からC++に構造体を送るサンプル(C++側処理) | |
#include <iostream> | |
typedef struct | |
{ | |
int id; | |
float value; | |
}StructData; | |
extern "C" __declspec(dllexport) void SendStruct(StructData* output, StructData* input) | |
{ | |
// outputのidに、inputのidに20加算した値を代入 | |
output->id = input->id + 20; | |
// outputのvalueに、inputのvalueに0.9999加算した値を代入 | |
output->value = input->value + 0.9999; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment