本文介绍了封送非托管的char **托管的String []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DLL文件(它被编译与多字节字符集选项)C ++函数:

I have a C++ function in a DLL file (it is compiled with the Multi-Byte Character Set option):

_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#原型必须是下一:

I suppose that the C# prototype must be next:

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



不过,我应该准备的IntPtr对象从非托管代码接收字符串?

But should I prepare IntPtr objects to receive strings from unmanaged code?

推荐答案

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

So OutBuff is basically an array of pointers - so you need to create an IntPtr array whose elements are valid pointers - that is IntPtr values that point to valid memory. Like below:

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]);
}

这篇关于封送非托管的char **托管的String []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 16:14