将 char*[] 从 C++ DLL 结构体传递到 C#

passing char*[] from c++ dll Struct to c#

本文关键字:结构体 DLL C++ char      更新时间:2023-10-16

我正在尝试通过c ++ DLL将以下结构传递给c#:

struct name 
{   char* myArray[3];
    char firstname[100]; 
    char lastname[100]; 
}; 
void Caller(struct name * demo) 
{
  strcpy(demo->firstname,"hello");
  demo->myArray[0]="hello";
  demo->myArray[1]="hello";
  demo->myArray[2]="hello";
  ping(demo);                     //call to c# function
}

下面是我的 c# 代码:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct name
{
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
   public string firstname;
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
   public string lastname;
   //what should i marshal here for  char* myArray[3];
} ;
static void Main(string[] args)
{
   name myname = new name();
   ping( ref myname);
}
public static void ping(int a,ref name myname)
{
   Console.WriteLine(myname.firstname+"n");
}

我能够从c ++ dll导入名字和姓氏。

我应该怎么做才能从 c++ 导入字符指针数组?

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Name
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
    public string FirstName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
    public string LastName;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
    public string[] Array;
};

对于我的完整解决方案,请检查 Foo.cpp 和程序.cs:https://gist.github.com/3779066