c#中的元帅char [] [LENGTH]

问题描述 投票:0回答:1

在C#项目中,我很难连接来自外部库的C ++函数。我想这是字符串编组的问题。

In C++ there is the following function:

int compute(const char names[][LENGTH_1], char values[][LENGTH_2], const int n);

目标是提供:

  • 包含LENGTH_1个字符的“n”个字符串的只读数组
  • 包含LENGTH_2个字符的“n”个字符串的可写数组

函数“compute”将根据“names”中指定的内容写入数组“values”。

In tried in C# two different ways to connect the function

方法1

[DllImport("abcd.dll", EntryPoint="compute", CharSet=CharSet.Ansi)]
internal static extern int Compute(StringBuilder [] names, StringBuilder [] values, int n);

我这样称呼它:

var names = new StringBuilder[number];
var descriptions = new StringBuilder[number];
for (int i = 0; i < number; i++) {
  names[i] = new StringBuilder(LENGTH_1);
  descriptions[i] = new StringBuilder(LENGTH_2);
}
var error = Compute(names, descriptions, number);

方法2

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=4)]
internal struct StringName
{
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst=64)] // LENGTH_1 = 64
  public string msg;
}

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=4)]
internal struct StringValue
{
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] // LENGTH_2 = 128
  public string msg;
}

[DllImport("abcd.dll", EntryPoint="compute", CharSet=CharSet.Ansi)]
internal static extern int Compute(StringName[] names, ref StringValue[] values, int number);

我这样称呼它:

var names = new StringNames[number];
var values = new StringValue[number];
var error = Compute(names, ref values, number);

Result

它没有例外地崩溃,程序在“Compute”功能上被阻止。我仍然不确定问题是来自字符串还是来自外部库。

c# c++ string marshalling dllimport
1个回答
0
投票

正如David所发现的那样,关键字“ref”是错误的。以下是方法2的更改。

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
internal struct StringName
{
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst=LENGTH_1)]
  public string msg;
}

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
internal struct StringValue
{
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst=LENGTH_2)]
  public string msg;
}

[DllImport("abcd.dll", EntryPoint="compute", CharSet=CharSet.Ansi)]
internal static extern int Compute([In] StringName[] names, [In, Out] StringValue[] values, int number);

我这样称呼它:

var names = new StringNames[number];
// ... here the initialization of "names" ... //
var values = new StringValue[number];
var error = Compute(names, values, number);
// ... here the processing of "values" ... //
© www.soinside.com 2019 - 2024. All rights reserved.