如何将指向char[256]数组的指针从C++编组到C#

How to marshall pointer to array of char[256] from C++ to C#

本文关键字:指针 C++ 数组 char      更新时间:2023-10-16

我有一个C++方法,它有以下签名:

typedef char TNameFile[256];
void Foo(TNameFile** output);

我已经没有办法整理它了。

假设它们返回一个空字符串作为最后一个元素:

static extern void Foo(ref IntPtr output);
IntPtr ptr = IntPtr.Zero;
Foo(ref ptr);
while (Marshal.ReadByte(ptr) != 0)
{
   Debug.Print(Marshal.PtrToStringAnsi(ptr, 256).TrimEnd(''));
   ptr = new IntPtr(ptr.ToInt64() + 256);
}

编辑:由于我已经在智能手机上写了上面的代码,我今天早上测试了代码,它似乎应该可以工作(我只需要添加TrimEnd(''))。这是我的测试用例:

class Program
{
    const int blockLength = 256;
    /// <summary>
    /// Method that simulates your C++ Foo() function
    /// </summary>
    /// <param name="output"></param>
    static void Foo(ref IntPtr output)
    {
        const int numberOfStrings = 4;
        byte[] block = new byte[blockLength];
        IntPtr dest = output = Marshal.AllocHGlobal((numberOfStrings * blockLength) + 1);
        for (int i = 0; i < numberOfStrings; i++)
        {
            byte[] source = Encoding.UTF8.GetBytes("Test " + i);
            Array.Clear(block, 0, blockLength);
            source.CopyTo(block, 0);
            Marshal.Copy(block, 0, dest, blockLength);
            dest = new IntPtr(dest.ToInt64() + blockLength);
        }
        Marshal.WriteByte(dest, 0); // terminate
    }
    /// <summary>
    /// Method that calls the simulated C++ Foo() and yields each string
    /// </summary>
    /// <returns></returns>
    static IEnumerable<string> FooCaller()
    {
        IntPtr ptr = IntPtr.Zero;
        Foo(ref ptr);
        while (Marshal.ReadByte(ptr) != 0)
        {
            yield return Marshal.PtrToStringAnsi(ptr, blockLength).TrimEnd('');
            ptr = new IntPtr(ptr.ToInt64() + blockLength);
        }
    }
    static void Main(string[] args)
    {
        foreach (string fn in FooCaller())
        {
            Console.WriteLine(fn);
        }
        Console.ReadKey();
    }
}

还有一个问题:谁将释放缓冲区

如果您使用C++/CLI而不是本机C++,您将不必担心不安全的代码和错误提示:

array<Byte>^ cppClass::cppFunction(TNameFile** input, int size)
{
    array<Byte>^ output = gcnew array<Byte>(size);
    for(int i = 0; i < size; i++)
        output[i] = (**input)[i];
    return output;
}

如果必须使用编组,请尝试使用Marshal.PtrToStringAnsi,正如WouterH在回答中所建议的那样。