将字符串从 C# 编组到 C++ 的 char[]

问题描述

我正在尝试将数据从 C# 编组到 C++ DLL。为此,我有以下 C++ 代码

// C++ Function in DLL
int __declspec(dllexport) DataAnalyze(AllInfo *&all)
{
   return 0;
}

// Structure
typedef struct
{
    char model[100];
    char log[_MAX_PATH];
    char path[_MAX_PATH];
}AllInfo;

这是我的 C# 代码

public unsafe void Execute()
{
  // Assigning values
  public AllInfo ana_alls = new AllInfo();
  AllInfo adt = new AllInfo(0);
  adt.Eye_img_num = 5;
  adt.Flow_log = @"D:\\HTML\\File.txt";
  adt.Pano_path = @"D:\\HTML\\Img.bmp";
  ana_alls = adt;

  // Preparing data for marshalling
  IntPtr intPtrsAll = new IntPtr();
  intPtrsAll = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(AllInfo)));
  Marshal.StructuretoPtr<AllInfo>(ana_alls,intPtrsAll,false);

  // DLL calling
  int ret = 0 - DataAnalyze(ref intPtrsAll);
}

// Structure
[StructLayout(LayoutKind.Sequential)]
public struct AllInfo
{
    public AllInfo(int n)
    {
        this.model = string.Empty;
        this.path = string.Empty;
        this.log = string.Empty;
    }

    [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 100)]
    public string model;   

    [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 260)]
    public string log;   

    [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 260)]
    public string path;  
}

// DLL Calling
[DllImport(@"D:\\HTML\\Data\\DLL\\Dara_Dll.dll",CallingConvention = CallingConvention.Cdecl)]
public static extern int DataAnalyze(ref IntPtr ana_all);

在 C++ 方法中,我在 AllInfo *&all 路径中获取数据如下:

path :{'\0','\0','D',':','\\','H','T','M','L','I','m','g','.','b','p',........}

我也得到了类似的日志输出。我不知道为什么 '\0' 在来自 C# 的 C++ 中每个 char[] 数据的 0 到 7 索引中添加。我哪里做错了?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)