我有包含結構的 C++ 代碼,我需要將它傳遞給 C#:包裝器.h#pragma oncetypedef struct{ int int1; int int2;} MY_STRUCT;MY_STRUCT mystruct;extern "C" __declspec(dllexport) int __stdcall GetTestStruct(MY_STRUCT* cs_struct);包裝器.cpp:int __stdcall GetTestStruct(MY_STRUCT* cs_struct){ mystruct.int1 = 23; mystruct.int2 = 45; cs_struct = &mystruct; return 0;}包裝器.cs:class Program{ [StructLayout(LayoutKind.Sequential)] public struct MY_STRUCT { public int int1; public int int2; } [DllImport(VpxMctlPath)] public static extern int GetTestStruct(ref MY_STRUCT mystruct); static void Main(string[] args) { var s = new MY_STRUCT(); GetTestStruct(ref s); }}運行此代碼后,s 的 int1 和 int2 仍然為零。我試圖將 C# 結構字段設置為私有和公共,但沒有區別。我查看了 C++/CLI,但這對于這個小任務來說似乎有些過分了。有沒有簡單的方法可以做到這一點?
1 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
更改 C++ 函數以直接在引用的結構上設置整數值:
int __stdcall GetTestStruct(MY_STRUCT* cs_struct)
{
cs_struct->int1 = 23;
cs_struct->int2 = 45;
//cs_struct = *mystruct; //This line may not be necessary
return 0;
}
- 1 回答
- 0 關注
- 81 瀏覽
添加回答
舉報
0/150
提交
取消