c# - 如何在 C++ 端将 SharedMemory 映射文件读出为不同的数据类型
问题描述
@首先,如果代码格式不起作用,我很抱歉,这是我的第一次尝试......
我正在 C# WPF 应用程序和 C++ DLL(由第 3 方应用程序使用)之间建立进程间通信。通信应用于通信几种不同的基本数据类型(bool、(u)integer、float、double、string)。因此,我计划将 MemoryMappedFile 用作未指定数据的字段,其大小适合我的数据量。我使用相同的 ConfigFile 读取双方的配置,然后将我的字节偏移量存储到另一个变量中。例如
//bool1 => memory[0]
//int1 => memory[1]
//float1 => memory[5]
//double1 => memory[9]
//int2 => memory[17] and so on...
但是我无法在没有异常的情况下重新解释 c++ 端的值。
SharedMemory 通信本身可以正常工作。我将数据从每一方发送到另一方。如果我在每个字段中用 1 填充 c# sid 上的 byte[],我可以将 c++ 端的整个缓冲区打印为字符,并且我会看到每个字段的 SOH(ascii 0x01)。
// read the MapViewOfFile ... works
auto buffer = (char*) MapViewOfFile(this->shm_handle,
FILE_MAP_READ, 0, 0, this->shm_field_size);
//interpret as std::string and print out
//makes a bunch of SOH SOH... in my logfile
std::string incomingPayload(buffer);
_HEILOG(incomingPayload);
//this line throws an exception (I´m not able to catch it)
int tmp_int = *reinterpret_cast<int*>(buffer, 0);
_HEILOG("field as int" << tmp_int);
// this block throws also an unknown exception...
void* v = (void*)buffer[0];int* ip = (int*)v;
int testi = *ip;
_HEILOG("field as int2" << testi );
我希望这两种尝试都可以工作,因为我希望能够通过buffer[offset]
(例如buffer[0]
,,buffer[1]
...buffer[5]
对于上面的示例)在内存字段中导航。
然后对即将到来的字节进行重新解释,以将数据读取为 bool、int、float 或其他形式。但是我的第 3 方应用程序引发了未知异常,并且我的日志文件没有条目。
我很感谢每一个提示。
最好的问候 SU52
编辑: 在 Selvins 的帮助下,我通过推迟 char[] 的值而不是 char[] 的地址来解决我的重大错误。
现在我在读取双精度值时仍然遇到问题:
/*
Double 355664.12 as binary in C#
Byte No[13] => 174 as Binary: 10101110
Byte No[14] => 71 as Binary: 01000111
Byte No[15] => 225 as Binary: 11100001
Byte No[16] => 122 as Binary: 01111010
Byte No[17] => 64 as Binary: 01000000
Byte No[18] => 181 as Binary: 10110101
Byte No[19] => 21 as Binary: 00010101
Byte No[20] => 65 as Binary: 01000001
*/
char doublefield[] = { BYTE(1010,1110),
BYTE(0100,0111),
BYTE(1110,0001),
BYTE(0111,1010),
BYTE(0100,0000),
BYTE(1011,0101),
BYTE(0001,0101),
BYTE(0100,0001)
};
double *double_p = reinterpret_cast<double*>(&doublefield[0]);
std::cout << double_p[0] << std::endl; //355664 missing decimals
导致缺少小数。
我尝试将 4 HiBytes 与 4 LoBytes 切换但没有成功。
有没有人有小数丢失的想法?BR
解决方案
推荐阅读
- python - 如何过滤包含列表中所有值的 DataFrame 列?
- flutter - Flutter http 在 releasebuild 中不起作用
- qgis - 如何从 wms 层导出 tiff?
- three.js - 如何保持合并几何的单独材料
- node.js - Socket.io 仅在 nodejs 中的服务器重启时发出
- c# - 无法在 Visual Studio Code 中运行 C#
- r - 模态拆分值的分组条形图
- sql-server - 通过 ASP.NET Core MVC 和 Entity Framework 刷新 SQL Server 表
- mongodb - Percona 在 kubernetes 上备份 mongodb
- unreal-engine4 - 虚幻引擎 4.26 在启动时不断崩溃(断言失败)