【问题标题】:Marshaling unmanaged char** to managed string[]将非托管 char** 编组为托管字符串 []
【发布时间】:2011-02-06 17:46:07
【问题描述】:

我在一个 DLL 文件中有一个 C++ 函数(它是使用多字节字符集选项编译的):

_declspec(dllexport) void TestArray(char** OutBuff,int Count,int MaxLength)
{
    for(int i=0;i<Count;i++)
    {
        char buff[25];
        _itoa(i,buff,10);

        strncpy(OutBuff[i],buff,MaxLength);
    }
}

我想C#原型一定是下一个:

    [DllImport("StringsScetch.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
    private static extern void TestArray([MarshalAs(UnmanagedType.LPArray)] IntPtr[] OutBuff, int Count, int MaxLength);

但是我应该准备 IntPtr 对象来接收来自非托管代码的字符串吗?

【问题讨论】:

  • 我也无法使用 StringBuilder[]。除了通过 Marshal.AllocHGlobal 编组之外,别无他法。
  • 是的,这种方法很有效!非常感谢!

标签: c# c++ string marshalling


【解决方案1】:

所以 OutBuff 基本上是一个指针数组——所以你需要创建一个 IntPtr 数组,其元素是有效指针——即指向有效内存的 IntPtr 值。如下:

int count = 10;
int maxLen = 25;
IntPtr[] buffer = new IntPtr[count];

for (int i = 0; i < count; i++)
    buffer[i] = Marshal.AllocHGlobal(maxLen);

TestArray(buffer, count, maxLen);

string[] output = new string[count];
for (int i = 0; i < count; i++)
{
    output[i] = Marshal.PtrToStringAnsi(buffer[i]);
    Marshal.FreeHGlobal(buffer[i]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多