将数组内存文件C++共享到C#



i尝试通过内存文件c++到c#共享一个数组,基于以下示例:通过共享内存将数据从c++流到c#。工作得很好,但我只能从数组中得到位置3,另一个位置为0。

创建MemoryFile 的C++

#include <windows.h>
#include <stdio.h>
struct Pair {
int length;
int data[10];
};
struct Pair* p;
HANDLE handle;
int dataSend[10]{ 500,33,44,66,2,55,98,7,52,36 };
bool startShare()
{
try
{
handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(Pair), L"DataSend");
p = (struct Pair*) MapViewOfFile(handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, sizeof(Pair));
return true;
}
catch (...)
{
return false;
}
}

int main()
{
if (startShare() == true)
{
printf("Memory Create");
while (true)
{
if (p != 0) {

for (int h = 0; h < 10; h++)
{
p->data[h] = dataSend[h];
printf("n number %d", dataSend[h]);
}
}

else
puts("create shared memory error");
}
}
if (handle != NULL)
CloseHandle(handle);
return 0;
}

我的C#读取

public static int[] data = new int[10];
public static MemoryMappedFile mmf;
public static MemoryMappedViewStream mmfvs;
static public bool MemOpen()
{
try
{
mmf = MemoryMappedFile.OpenExisting("DataSend");
mmfvs = mmf.CreateViewStream();
return true;
}
catch
{
return false;
}
}
public static void Main(string[] args)
{
while (true)
{
if (MemOpen())
{
byte[] blen = new byte[4];
mmfvs.Read(blen, 0, 4);
byte[] bPosition = new byte[280];
mmfvs.Read(bPosition, 0, 280);
Buffer.BlockCopy(bPosition, 0, data, 0, bPosition.Length);
for (int i = 0; i < data.Length; i++)
{
Console.WriteLine(data[i]);
}
}
}
}

工作得很好,但我只能从数组中得到位置3,另一个位置为0。

更新,代码现在工作正常只是一个细节,我返回一个数组十六进制值示例:52A7E600但在我的代码c#中,得到的比特数是:10300071984,我怎么不能在c端转换成相同的格式呢?

要在c#中将长值转换为十六进制,可以使用:

long intValue = 10300071984;
// Convert long value 10300071984 -> 265EEA030 as a hex in a string variable
string hexValue = intValue.ToString("X"); 

最新更新