gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:31:16 25 4
gpt4 key购买 nike

我有具有以下签名的 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('\0'));
ptr = new IntPtr(ptr.ToInt64() + 256);
}

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

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('\0');
ptr = new IntPtr(ptr.ToInt64() + blockLength);
}
}

static void Main(string[] args)
{
foreach (string fn in FooCaller())
{
Console.WriteLine(fn);
}
Console.ReadKey();
}
}

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

关于c# - 如何将指向 char[256] 数组的指针从 C++ 编码到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11646408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com