gpt4 book ai didi

c++ - 将结构指针转换为双指针

转载 作者:行者123 更新时间:2023-11-28 06:28:56 25 4
gpt4 key购买 nike

我有以下结构:

typedef struct 
{
double r, i;
} doublecomplex;

我想将 doublecomplex* 转换为 double*。可能吗?

我开始使用 OpenBlas,它具有复杂值的 double* 参数。我还想知道是否有可能进行相反的转换,因为某些函数返回 openblas_complex_double 这是:

typedef struct { double real, imag; } openblas_complex_double;

最佳答案

这两种类型都是布局兼容 standard layout 中的类型.因此,C++ 标准保证指向任一 struct 的指针可以安全地reinterpret_casted 为指向其第一个数据成员的指针。

double
get_real_part(const doublecomplex *const ptr)
{
static_assert(std::is_standard_layout<doublecomplex>::value,
"cast of non-standard layout type is not safe");
const double *const realptr = reinterpret_cast<const double *>(ptr);
return *realptr;
}

但是请注意,虽然这是允许的,但它仍然是一种相当糟糕的风格,您必须非常小心,不要智取自己。如果有办法避免这样做,您应该这样做。

此外,请不要typedef C++ 中的struct。完全没有必要。

关于c++ - 将结构指针转换为双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28003014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com