【发布时间】:2011-08-10 13:28:45
【问题描述】:
我有一个非托管 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 字节值,不是以 null 结尾的。
任何人都可以对此有所了解吗?谢谢!
斯图尔特
【问题讨论】:
标签: c# c++ interop pinvoke marshalling