【发布时间】:2020-04-24 21:49:11
【问题描述】:
所以基本上我试图比较两个来自 Vulkan 的 VkPhysicalDeviceFeatures,一个来自我正在查看的 VkPhysicalDevice,另一个对应于我实际需要的一组功能。 VkPhysicalDeviceFeatures struct only 包含 VkBool32 成员(它们是 uint32_t 的类型定义),但 vulkan 的每个次要版本都可以添加未知数量的这些功能。我想做的只是将每个结构的成员相互比较,而不是为了相等,更多的是逻辑比较。如果物理设备结构中的相应成员为假,但我的结构对该成员具有真,那么比较应该返回假。
我能想到的唯一方法就是this answer 发布的内容:
bool hasRequiredFeatures(VkPhysicalDevice physical_device,
VkPhysicalDeviceFeatures required_features) {
VkPhysicalDeviceFeatures physical_device_features = getSupportedFeatures(physical_device);
std::size_t struct_length = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
auto physical_device_features_bool_ptr = reinterpret_cast<VkBool32*>(&physical_device_features);
auto required_features_bool_ptr = reinterpret_cast<VkBool32*>(&required_features);
for(std::size_t i = 0; i < struct_length; ++i){
if(physical_device_features_bool_ptr[i] == VK_FALSE && required_features_bool_ptr[i] == VK_TRUE){
return false;
}
}
return true;
}
这可以满足我的要求(尽管有一种方法可以通过名称查看哪个特定成员未能通过比较,但我想如果没有反射这是不可能的)但我认为 C++ 不能保证严格对齐像这样?我有没有跨平台的方式来完成这个?
【问题讨论】:
-
最安全的选择可能是
magic_get。关于您的方法:虽然理论上不能保证缺少填充,但在这种情况下,编译器不需要添加它(除非以某种方式涉及alignas)。但如果我没记错的话,像这样在reinterpret_castedVkBool32上进行指针运算就是UB。我认为在char *上进行算术运算(然后将指针转换为正确的类型)是明确定义的,但我不是 100% 确定。
标签: c++ struct c++17 vulkan struct-member-alignment