我有包含结构的C ++代码,我需要将其传递给C#:
wrapper.h
#pragma once
typedef struct
{
int int1;
int int2;
} MY_STRUCT;
MY_STRUCT mystruct;
extern "C" __declspec(dllexport) int __stdcall GetTestStruct(MY_STRUCT* cs_struct);
wrapper.cpp:
int __stdcall GetTestStruct(MY_STRUCT* cs_struct)
{
mystruct.int1 = 23;
mystruct.int2 = 45;
cs_struct = &mystruct;
return 0;
}
wrapper.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,但这似乎对这个小任务来说太过分了。有没有简单的方法可以做到这一点?
答案 0 :(得分:1)
更改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;
}