gpt4 book ai didi

c# - C++ <--> C# 修改编码的字节数组

转载 作者:行者123 更新时间:2023-11-30 02:08:20 25 4
gpt4 key购买 nike

我有一个非托管 C++ 函数,它在 DLL 中调用托管 C# 方法。 C# 方法的目的是获取字节数组(由 C++ 调用程序分配)、填充数组并返回它。我可以通过 C# 方法获取数组,但是填充的数据在返回到 C++ 函数时丢失了。现在,这是我调试过程的测试代码:

C# DLL 方法:

// Take an array of bytes and modify it
public ushort GetBytesFromBlaster([MarshalAs(UnmanagedType.LPArray)] byte[] dataBytes)
{
dataBytes[0] = (byte)'a';
dataBytes[1] = (byte)'b';
dataBytes[2] = (byte)'c';
return 3;
}

调用 DLL 的 C++ 函数:

// bytes[] has been already allocated by its caller
short int SimGetBytesP2P(unsigned char bytes[])
{
unsigned short int numBytes = 0;
bytes[0] = 'x';
bytes[1] = 'y';
bytes[2] = 'z';
// bytes[] are {'x', 'y', 'z'} here
guiPtr->GetBytesFromBlaster(bytes, &numBytes);
// bytes[] SHOULD be {'a', 'b', 'c'} here, but they are still {'x', 'y', 'z'}
return(numBytes);

我相信这与 C# 将 C++ 指针转换为新的托管数组,但修改了原始数组有关。我已经使用“ref”修改器等尝试了几种变体,但没有成功。此外,这些数据不是以 null 结尾的字符串;日期字节是原始的 1 字节值,不是空终止的。

任何人都可以阐明这一点吗?谢谢!

斯图尔特

最佳答案

您可以自己进行编码。让 C# 函数接受 IntPtr 类型值的参数。还有一个指示数组长度的第二个参数。不需要或不需要特殊的编码属性。

然后,使用 Marshal.Copy 并将数组从非托管指针复制到您分配的托管 byte[] 数组。执行您的操作,然后在完成后使用 Marshal.Copy 将其复制回 C++ 非托管数组。

这些特定的重载应该让你开始:

http://msdn.microsoft.com/en-us/library/ms146625.aspx
http://msdn.microsoft.com/en-us/library/ms146631.aspx

例如:

public ushort GetBytesFromBlaster(IntPtr dataBytes, int arraySize)
{
byte[] managed = new byte[arraySize];
Marshal.Copy(dataBytes, managed, 0, arraySize);
managed[0] = (byte)'a';
managed[1] = (byte)'b';
managed[2] = (byte)'c';
Marshal.Copy(managed, 0, dataBytes, arraySize);
return 3;
}

或者,您可以实现自定义编码器,如 http://msdn.microsoft.com/en-us/library/w22x2hw6.aspx 中所述。如果默认的没有做你需要它做的事。但这看起来需要更多工作。

关于c# - C++ <--> C# 修改编码的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7011567/

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