我试图使用联合来更新一个线程中的字段,然后读取另一个线程中的所有字段。在实际系统中,我有互斥锁以确保一切安全。问题在于 fieldB,在我不得不更改它之前 fieldB 被声明为字段 A 和 C。但是,由于第三方驱动程序,fieldB 必须与页面边界对齐。当我将字段 B 更改为使用 valloc 分配时,我遇到了问题。
问题:1)有没有办法静态声明 fieldB 在页面边界上对齐。基本上和valloc做同样的事情,但是在堆栈上?
2) 是否可以在字段 B 或堆上分配任何字段时进行联合?不确定这是否合法。
这是我正在试验的一个简单的测试程序。除非您像字段 A 和 C 一样声明字段 B,并在公共方法中进行明显更改,否则这不起作用。
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
class Test
{
public:
Test(void)
{
// field B must be alligned to page boundary
// Is there a way to do this on the stack???
this->field.fieldB = (unsigned char*) valloc(10);
};
//I know this is bad, this class is being treated like
//a global structure. Its self contained in another class.
unsigned char* PointerToFieldA(void)
{
return &this->field.fieldA[0];
}
unsigned char* PointerToFieldB(void)
{
return this->field.fieldB;
}
unsigned char* PointerToFieldC(void)
{
return &this->field.fieldC[0];
}
unsigned char* PointerToAllFields(void)
{
return &this->allFields[0];
}
private:
// Is this union possible with field B being
// allocated on the heap?
union
{
struct
{
unsigned char fieldA[10];
//This field has to be alligned to page boundary
//Is there way to be declared on the stack
unsigned char* fieldB;
unsigned char fieldC[10];
} field;
unsigned char allFields[30];
};
};
int main()
{
Test test;
strncpy((char*) test.PointerToFieldA(), "0123456789", 10);
strncpy((char*) test.PointerToFieldB(), "1234567890", 10);
strncpy((char*) test.PointerToFieldC(), "2345678901", 10);
char dummy[11];
dummy[10] = '\0';
strncpy(dummy, (char*) test.PointerToFieldA(), 10);
printf("%s\n", dummy);
strncpy(dummy, (char*) test.PointerToFieldB(), 10);
printf("%s\n", dummy);
strncpy(dummy, (char*) test.PointerToFieldC(), 10);
printf("%s\n", dummy);
char allFields[31];
allFields[30] = '\0';
strncpy(allFields, (char*) test.PointerToAllFields(), 30);
printf("%s\n", allFields);
return 0;
}