gpt4 book ai didi

c++ - 将reinterpret_cast 指针传递为void *

转载 作者:行者123 更新时间:2023-11-30 01:08:32 26 4
gpt4 key购买 nike

如下code -

#include <iostream>
using namespace std;

struct S1{
int a; int b; int c; int d;
};

struct S{
int a; int b;
};

int main() {
S1 obj1;
obj1.a = 1;
obj1.b = 2;
obj1.c = 3;
obj1.d = 4;

cout << obj1.a << " "
<< obj1.b << " "
<< obj1.c << " "
<< obj1.d << "\n";

// more code

auto ptr = reinterpret_cast<S *>(&obj1);
cout << ptr->a << " " << ptr->b << "\n";

// more code

// someFunc(ptr, sizeof(obj1));
}

我将值分配给结构 S1 的成员,然后通过 reinterpret_cast 原始 S1 将它们用作结构 S 指针到S。这工作得很好。

现在,我有一个函数 someFunc(const void *ptr, int len) ,它接受一个 const void * 指针和指向结构的长度通过了。在这种情况下,需要将 S1 结构传递给它,并且在它内部有一些 memcpy 调用来复制该结构并处理该拷贝。 那我可以这样做吗? -

// more code

someFunc(ptr, sizeof(obj1));
}

意味着将reinterpret_casted指针传递给该函数以及原始S1结构的大小,或者我是否必须再次reinterpret_cast将其返回S1,然后再次传递指针。

不必再次reinterpret_cast到原始类型将为我节省一些类似类型(如S1)的切换情况。请注意,someFunc 可以根据传入的 size 轻松找出类型,因为那些相似的类型在大小上差异很大。

最佳答案

结构体的地址是该结构体的第一个字节的地址。即使我在标准中找不到它的任何引用,将指向 POD 结构(或多或少是 C 结构)的指针转换为指向初始子序列的指针也是 C++ 中的常见习惯用法(就像在 C 中一样)那个类(class)的。当转换为 void * 时,两者将给出相同的值。

所以用你的符号:

someFunc(ptr, sizeof(obj1));

someFunc(obj1, sizeof(obj1));

是完全相同的调用。

关于c++ - 将reinterpret_cast 指针传递为void *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42366614/

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