Struct 使用注意:
1.C中,结构体中,double类型 及其数组类型应该放一起。
2.double类型数组不能放置在结构体最后位置。
3.将结构体中变量类型按照字节长度从高到低放置,保证python数据读取正确 double 8个byte,int ,long4个, short2个,bool1个,char1个的顺序排列
错误:
class student
{
public:
double dValue;
int ID;
double b[5];
char name[20];
int a[5];
student()
{
ID = 0;
memset(name, '\0', sizeof(name));
dValue = 0;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
}
};
class student
{
public:
int ID;
char name[20];
int a[5];
double dValue;
double b[5];
student()
{
ID = 0;
memset(name, '\0', sizeof(name));
dValue = 0;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
}
};
正确:
class student
{
public:
double dValue;
double b[5];
int ID;
char name[20];
int a[5];
student()
{
ID = 0;
memset(name, '\0', sizeof(name));
dValue = 0;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
}
};
win7下正确读取方式:
win32 VC++
// ShareData.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
class student
{
public:
double dValue;
double b[5];
int ID;
char name[20];
int a[5];
student()
{
ID = 0;
memset(name, '\0', sizeof(name));
dValue = 0;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
}
};
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hMemShare;
student stu;
int stu_num = 30;
student *lpstu;
stu.ID = -100;
strcpy_s(stu.name,"huangguangzhi");
stu.dValue=0;
hMemShare = CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE,0,sizeof(student),_T("TestMemShare"));
if(hMemShare == NULL)
{
cout<<"Failed to Alloocate"<<endl;
return 1;
}
lpstu = (student *)MapViewOfFile(hMemShare, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, sizeof(student));
if(lpstu == NULL)
{
cout<<"Failed to Map"<<endl;
return 1;
}
*lpstu = stu;
while(1){
lpstu->dValue += 0.001;
lpstu->a[0] = 1;
lpstu->a[1] = -20;
lpstu->a[2] = 300;
lpstu->a[3] = -40000;
lpstu->a[4] = 600000;
lpstu->b[0] = 1.5646546;
lpstu->b[1] = 1.6757575;
lpstu->b[2] = 1.56565;
lpstu->b[3] = 1.77777;
lpstu->b[4] = 1.999999;
cout << lpstu->ID << endl;
cout << lpstu->name << endl;
cout << lpstu->dValue << endl;
cout << lpstu->a[0] << endl;
cout << lpstu->a[1] << endl;
cout << lpstu->a[2] << endl;
cout << lpstu->a[3] << endl;
cout << lpstu->a[4] << endl;
cout << lpstu->b[0] << endl;
cout << lpstu->b[1] << endl;
cout << lpstu->b[2] << endl;
cout << lpstu->b[3] << endl;
cout << lpstu->b[4] << endl;
Sleep(1000);
}
UnmapViewOfFile(lpstu);
CloseHandle(hMemShare);
return 0;
}
python:
import mmap
import contextlib
import sys
import time
import struct
while True:
with contextlib.closing(mmap.mmap(-1, 1024, tagname='TestMemShare', access=mmap.ACCESS_READ)) as m:
print(m.read_byte())
s = m.read(1024)
print(s)
byOrder = sys.byteorder
a = ()
#ID, Name, Value, a0, a1, a2, a3, a4, b0, b1, b2, b3, b4 = struct.unpack("<di5d20s5i", m[:92])
a = a+struct.unpack("<6d1i20s5i", m[:92])
print(a)
time.sleep(1)