我正在尝试通过托管内存文件将c#中的整数数组传递给c ++。文本很容易实现,但是我在c ++环境中不够深入,并且不确定如何针对整数数组调整它。
在c#方面,我通过了:
pView = LS.Core.Platforms.Windows.Win32.MapViewOfFile(
hMapFile, // Handle of the map object
LS.Core.Platforms.Windows.Win32.FileMapAccess.FILE_MAP_ALL_ACCESS, // Read and write access
0, // High-order DWORD of file offset
ViewOffset, // Low-order DWORD of file offset
ViewSize // Byte# to map to the view
);
byte[] bMessage2 = Encoding.Unicode.GetBytes(Message2 + '\0');
Marshal.Copy(bMessage2, 0, pView2, bMessage2.Length);
这里pView2是指向内存映射文件的指针。
在c ++方面,我打电话给:
LPCWSTR pBuf;
pBuf = (LPCWSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
我如何更改此处理而不是处理整数数组?谢谢!
答案 0 :(得分:1)
a)您可以将int []复制到byte []中。您可以将BitConverter.GetBytes用于此算术或位算术(byte0 =(byte)(i>> 24); byte1 =(byte)(i>> 16); ...)
b)您可以使用不安全的代码将int []按位复制(blit)到目标字节[]
c)也许你可以使用Array.Copy。我认为它可以处理任何blittable值类型。
根据评论我将详细说明b):
int[] src = ...;
IntPtr target = ...;
var bytesToCopy = ...;
fixed(int* intPtr = src) {
var srcPtr = (byte*)intPtr;
var targetPtr = (byte*)target;
for(int i from 0 to bytesToCopy) {
targetPtr[i] = srcPtr[i];
}
}