经过一些测试,我认为这个问题的答案是:取决于编译器和类。我将在下面给出的示例是在 Linux 上使用 GCC 和 G++ 编译的(似乎也可以使用 clang 和 clang++)。
示例 1 - 具有一些变量、构造函数、析构函数和重载函数的类 - 没什么特别之处。
//C++ class
class test
{
private:
int number;
char* string;
public:
test() { this->number = 0; this->string = (char*)""; this->boolean = false; }
~test() { }
void function(int num) { this->number = num; }
void function(char* str) { this->string = str; }
int get_number() { return this->number; }
char* get_string() { return this->string; }
bool boolean;
};
//C structure
//To create a struct pointer for this class, I just had to ignore the functions.
struct test_t
{
int number;
char* string;
bool boolean;
};
示例 2 - 一个包含虚函数的类。在这种情况下,我们必须在结构的开头添加一个额外的指针参数。这将与该类的虚函数表对齐,由于虚函数而不再隐藏。
//C++ class
class test
{
private:
int number;
char* string;
public:
test() { this->number = 0; this->string = (char*)""; this->boolean = false; }
~test() { }
virtual void v_function() { printf("virtual function\n"); }
virtual void v_function2() { printf("another virtual function\n"); }
void function(int num) { this->number = num; }
void function(char* str) { this->string = str; }
int get_number() { return this->number; }
char* get_string() { return this->string; }
bool boolean;
};
//C structure
//It is the same as before, but with the VFT pointer
struct test_t
{
void** vptr; //A pointer to function addresses (void**)
int number;
char* string;
bool boolean;
};
总之,100% 确保 C 结构指针与 C++ 类对齐的唯一方法是查看内存并手动对齐。你可以通过在你的结构中放置垫子来跳过一些变量:
//C++ class
class test
{
private:
int number;
std::vector<std::string> vector;
char* string;
public:
test() { this->number = 0; this->string = (char*)""; this->boolean = false; }
~test() { }
virtual void v_function() { printf("virtual function\n"); }
virtual void v_function2() { printf("another virtual function\n"); }
void function(int num) { this->number = num; }
void function(char* str) { this->string = str; }
int get_number() { return this->number; }
char* get_string() { return this->string; }
bool boolean;
};
//C structure
struct test_t
{
void** vptr;
int number;
char vector[24]; //std::vector<std::string> pad (24 bytes long)
char* string;
bool boolean;
};