6
공유 메모리를 사용하여 C++ 응용 프로그램에서 C# 응용 프로그램으로 데이터를 스트리밍하려고합니다. 내가 찾은 예를 바탕으로, 내가 가진 :스트림 데이터가 C++에서 C#으로 공유 메모리에 있습니다.
C++, (수신)
struct Pair {
int length;
float data[3];
};
#include <windows.h>
#include <stdio.h>
struct Pair* p;
HANDLE handle;
float dataSend[3]{ 22,33,44 };
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)
{
while (true)
{
if (p != 0) {
//dataSend[0] += 1; // here the value doesn't refresh
for (int h = 0; h < 3; h++)
{
p->data[h] = dataSend[h];
}
//dataSend[0] += 1; // here it does
}
else
puts("create shared memory error");
}
}
if (handle != NULL)
CloseHandle(handle);
return 0;
}
C#을
namespace sharedMemoryGET
{
class Program
{
public static float[] data = new float[3];
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);
int len = blen[0] + blen[1] * 256 + blen[2] * 65536 + blen[2] * 16777216;
byte[] bPosition = new byte[12];
mmfvs.Read(bPosition, 0, 12);
Buffer.BlockCopy(bPosition, 0, data, 0, bPosition.Length);
Console.WriteLine(data[0]);
}
}
}
}
}
의 C++ 쪽이 변수를 업데이트하지를 (전송) 나 내가 뭔가를 놓친 생각하고 내 if 루프에서. 또한 항상 실행중인 루프가 여기에 가장 좋은 방법입니까? C# 측에서 어떻게 든 데이터를 요청하여 더 효율적인 시스템으로 만들 수있는 방법이 있습니까? 고맙습니다.