C++ Class or Struct compatiblity with C struct(C++ 类或结构与 C 结构的兼容性)
问题描述
是否可以编写一个与C struct 完全兼容的C++ 类或结构.从兼容性我的意思是对象的大小和变量的内存位置.我知道使用 *(point*)&pnt 甚至 (float*)&pnt (在变量是浮点数的不同情况下)是邪恶的,但请考虑出于性能考虑,它确实需要.每秒使用百万次常规类型转换运算符是不合逻辑的.
Is it possible to write a C++ class or struct that is fully compatible with C struct. From compatibility I mean size of the object and memory locations of the variables. I know that its evil to use *(point*)&pnt or even (float*)&pnt (on a different case where variables are floats) but consider that its really required for the performance sake. Its not logical to use regular type casting operator million times per second.
举个例子
Class Point {
long x,y;
Point(long x, long y) {
this->x=x;
this->y=y;
}
float Distance(Point &point) {
return ....;
}
};
C 版本是一个 POD 结构
C version is a POD struct
struct point {
long x,y;
};
推荐答案
是.
- 在两种语言中以相同的顺序使用相同的类型
- 确保类中没有任何虚拟对象(这样您就不会在前面卡住 vtable 指针)
- 根据所使用的编译器,您可能需要调整结构包装(通常使用编译指示)以确保兼容性.
(编辑)
- 此外,您必须注意使用编译器检查类型的 sizeof().例如,我遇到过一个编译器将 short 存储为 32 位值(当大多数将使用 16 位值时).更常见的情况是 int 在 32 位架构上通常为 32 位,而在 64 位架构上通常为 64 位.
这篇关于C++ 类或结构与 C 结构的兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 类或结构与 C 结构的兼容性
基础教程推荐
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
