[英]How to marshall pointer to array of char[256] from C++ to C#
我有具有以下簽名的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 ++ / 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在其答案中建議的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.