我正在尝试使用内存映射文件将来自C++的结构共享到C#,到目前为止,我已经成功地向文件中写入了数据,但是我无法在C#中读取内容。
- C++中的SendData
struct Bus_1553 // this is the structure to send
{
string name;
int directions;
};
struct Bus_1553* p_1553; // set the pointer to it
HANDLE handle; // create the handle
// here we define the data to send
string name = "IFF";
int directions = 3;
bool startShare() // Open the shared memory
{
try
{
handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(Bus_1553), L"DataSend");
p_1553 = (struct Bus_1553*) MapViewOfFile(handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, sizeof(Bus_1553));
return true;
}
catch (...)
{
return false;
}
}
int main()
{
if (startShare() == true)
{
while (true)
{
if (p_1553 != 0) // populate the memory
{
p_1553->name = name;
p_1553->directions = directions;
}
else
puts("create shared memory error");
}
}
if (handle != NULL)
CloseHandle(handle);
return 0;
}
- 尝试在C#中读取数据
namespace sharedMemoryGET
{
class sharedMemoryGET
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct Bus_Data_1553
{
public string name;
public int directions; // which directions used
}
public static MemoryMappedFile mmf;
public static MemoryMappedViewStream mmfvs;
static public bool MemOpen() // open the mapped file
{
try
{
mmf = MemoryMappedFile.OpenExisting("DataSend");
return true;
}
catch
{
return false;
}
}
public static void readData()
{
if (MemOpen())
{
using (var accessor = mmf.CreateViewAccessor())
{
accessor.Read(0, out Bus_Data_1553 a);
Console.WriteLine(a.name);
Console.WriteLine(a.directions);
}
}
}
}
}
当结构中存在字符串时进行共享,我遇到了以下错误:指定的类型必须是不包含引用的结构体。
当我移除字符串并仅共享整数方向时,我得到了一个值为0。是否有人可以帮我解决这个问题?
std::string
和C#中的string
不同。由于std::string
是成员之一,所以你传递的struct
不是平凡可复制类型。此外,sizeof(Bus_1553)
并不像你想的那样工作。如果std::string
有一千个字符,sizeof(Bus_1553)
的大小不会改变,因为sizeof
是编译时的值,而不是运行时的值。 - PaulMcKenzieBus_1553
是一个标准布局结构体来实现,然后你可以在C#端使用Marshal.PtrToStructure
。 - Etienne de Martelchar name[128]
和在C#中相应的封送字符串[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string name;
。然而,我仍然得到了指定的类型必须是不包含引用的结构体。参数名: type
的错误提示。 - angie866