在C ++中使用C#嵌套结构

时间:2015-09-15 12:22:00

标签: c# c++ struct pinvoke marshalling

我在那个问题之前问过。

How to pass C++ Struct To C# DLL ?

现在我正在尝试嵌套struct marshal。

我已经取代了那样的结构。

typedef struct TKeyValue
{
  char Key[15];
  char Value[15];
} TKeyValue;

typedef struct MyStruct
{
  TKeyValue *KeyValues[1];
} TMyStruct;
typedef int (__stdcall *DoSomething)(char [],char[],TMyStruct *);

调用DLL函数

void __fastcall TForm1::btnInvokeMethodClick(TObject *Sender)
{
  wchar_t buf[256];
  String DLL_FILENAME = "ClassLibrary1.dll";
  HINSTANCE dllHandle = NULL;

  dllHandle = LoadLibrary(DLL_FILENAME.c_str());

  FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
  OutputDebugStringW(buf);

  if(dllHandle == NULL) return;

  DoSomething xDoSomething = (DoSomething)GetProcAddress(dllHandle, "DoSomething");
  FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
  OutputDebugStringW(buf);

  if (xDoSomething == NULL) return;

  try
  {
      TMyStruct aMyStruct;

      char parameter1[15];
      char parameter2[15];
      strcpy(parameter1,"value1");
      strcpy(parameter2,"value2");

      int result = xDoSomething(parameter1,parameter2,&aMyStruct);

      FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
      OutputDebugStringW(buf);

      //access violation at this line
      ShowMessage(aMyStruct.KeyValue[0]->Key);
  }
  catch(EAccessViolation &err)
  {
    ShowMessage(err.Message);
  }

  FreeLibrary(dllHandle);

C#Side

    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct KeyValue
    {
        [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]
        public string Key;

        [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]
        public string Value;
    }



    [ComVisible(true)]
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct MyStruct
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
        public KeyValue[] KeyValues;
    }

        [DllExport("DoSomething", CallingConvention = CallingConvention.StdCall)]
    public static int DoSomething(string tcKnVkn, string sifre, ref MyStruct myStruct)
    {
        try
        {
            MyStruct.KeyValues[0].Key = "key 1";
            MyStruct.KeyValues[0].Value = "value 1";
        }
        catch (Exception e)
        {
            System.Windows.Forms.MessageBox.Show(e.Message);
        }

        return 2;
    }

当我编译项目并运行时,它会在访问TKeyValue的Key字段后抛出访问冲突错误,如aMyStruct.KeyValue[0]->Key

我错了什么?

感谢。

1 个答案:

答案 0 :(得分:0)

此处的问题是您的Arrays字段。 C ++声明是:

char *Array[3];           // 3 pointers, uses up 12 bytes (32bit system)

这意味着一个3个指针的数组。停一下,考虑一下字符串还有多远 - 它不是一个连续的内存块,有你正在传递的字符,你传递号码。如果你想传递3个C字符串,你可以这样声明它(不是你顺便发送的东西,你需要在C#端有不同的属性):

char Array[15][3];        // 3 strings, uses up 45 bytes

您在这些指针中发送垃圾,当C代码尝试取消引用它们时,它会受到访问冲突。