微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将字符串从 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 举报,一经查实,本站将立刻删除。