为了账号安全,请及时绑定邮箱和手机立即绑定

p/invoke 方法返回空结构

p/invoke 方法返回空结构

C#
长风秋雁 2022-12-24 14:32:14
我有包含结构的 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;

}


查看完整回答
反对 回复 2022-12-24
  • 1 回答
  • 0 关注
  • 48 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信