p/invoke 方法返回空结构

我有包含结构的 C++ 代码,我需要将它传递给 C#:


包装器.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);

包装器.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,但这对于这个小任务来说似乎有些过分了。有没有简单的方法可以做到这一点?


长风秋雁
浏览 51回答 1
1回答

MMTTMM

更改 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;}
打开App,查看更多内容
随时随地看视频慕课网APP