c# - 如何将 C++ 结构传递给 C# DLL?

标签 c# c++ struct pinvoke marshalling

我在下面有一个 C# DLL。我想在 C++ Builder 中使用这个 C# DLL。

但我不知道 C# Struct 和 C++ Struct 编码:

using RGiesecke.DllExport;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace TestLibrary
{

    [ComVisible(true)]
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct MyStruct
    {
        public int X;
        public int Y;
    }


    public class Class1
    {
        [DllExport("DoSomething", CallingConvention = CallingConvention.StdCall)]
        public static int DoSomething(int x, int y, ref MyStruct myStruct)
        {
            myStruct.X = 50;
            myStruct.Y = 75;
            return x + y;
        }

    }
}

我想从下面的 C++ Builder 传递“myStruct”参数。

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  struct MyStruct
  {
    int X;
    int Y;
   };

  int (__stdcall *DoSomething)(int,int,MyStruct);


  HINSTANCE dllHandle = NULL;
  dllHandle = LoadLibrary( edtdllPath->Text.c_str());
  if(dllHandle == NULL) return;
  int status = -1;

  try
  {
    DoSomething =(int (__stdcall *)(int,int,MyStruct)) GetProcAddress(dllHandle, "DoSomething");
  }
  catch(Exception &Err)
  {
    ShowMessage(Err.Message);
  }

  if(DoSomething != NULL)
  {
    try
    {
      MyStruct myStruct;
      status = DoSomething(5,5,myStruct);
      String strStatus = status;

      ShowMessage(strStatus);
      ShowMessage(myStruct.X);
      ShowMessage(myStruct.Y);
    }
    catch(EAccessViolation &err)
    {
     ShowMessage(err.Message);
    }
  }

}

当我调试代码时,myStruct.X 和 myStruct.Y 值是错误的。

我哪里错了?

最佳答案

您没有将您的结构作为指向 c# 的指针传递,但在 c# 中您告诉它它将是一个指针 (ref)。

关于c# - 如何将 C++ 结构传递给 C# DLL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32502499/

相关文章:

c# - 在 WPF 中验证文本框时启用按钮

c# - 匹配所有美国电话号码格式的正则表达式

c++ - 如果表达式的求值需要对引用求值,为什么表达式不是 "core constant expression"?

c++ - 更改函数的输入类型

在结构中创建指向数组的指针

C 全局结构 : "error: expected expression before ' {' token"

c# - 从 Windows 服务播放 wave 文件 (C#)

C# 如何将数字作为 float 传递给函数?

c# - 无法启动程序,Windows Web 服务框架中出现无法识别的错误

c - 初始化包含指向数组的指针的结构