以独立于实现的方式获取指向 4 字节对象的指针

发布于 2024-08-22 12:03:58 字数 479 浏览 1 评论 0原文

当我意识到假设 int 将是指向 4 个字节长度的指针可能并不完全安全时,我正在正常编程。

因为一些方面C++ 的基本类型(例如 int 的大小)是实现定义的。

如果您正在处理具有 32 位有符号整数样本的内容(例如波形),该怎么办?您将字节指针转换为 (int*) 并一次处理一个样本。

我只是好奇获取 4 字节指针的“安全方法”是什么,如果将来的某个时候 MSVC 委员会决定 int 现在是 8 字节,那么该指针不会停止工作。

相关

I was programming normally when I realized that its probably not perfectly safe to assume an int is going to be a pointer to something 4 bytes in length.

Because Some of the aspects of C++’s fundamental types, such as the size of an int, are implementation- defined..

What if you're dealing with something (like a waveform, for example) that has 32-bit signed integer samples. You cast the byte pointer to (int*) and deal with it one sample at a time.

I'm just curious what's the "safe way" to acquire a 4-byte pointer, that ISN'T going to stop working if sometime in the future MSVC committee decides int is now 8 bytes.

Related

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

相思故 2024-08-29 12:03:58

您的编译器有一个名为 stdint.h 的 C99 标头可能有。它定义了诸如 uint32_t 之类的类型,即无符号 32 位整数。

从 C++11 开始,您的编译器需要具有此标头。您应该将其包含在 #include 中。

如果没有,请查看 Boost Integer,它将此标头模仿为


要将指针存储为整数,请使用在同一标头中定义的 intptr_t

There is a C99 header called stdint.h your compiler might have. It defines types like uint32_t, an unsigned 32-bit integer.

Since C++11, your compiler is required to have this header. You should include it with #include <cstdint>.

If not, check out Boost Integer, which mimics this header as <boost/cstdint.hpp>.


For storing pointers as integers, use intptr_t, defined in the same header.

压抑⊿情绪 2024-08-29 12:03:58

使用指向 uint32_t 的指针而不是 int。

此类型(和其他类型)在 stdint.h 中定义,并且是 C99 标准的一部分

Use a pointer to uint32_t instead of int.

this type (and others) is defined in stdint.h and is part of the C99 standard

四叶草在未来唯美盛开 2024-08-29 12:03:58

我见过的一种方法是使用预编译器指令和 typedef 抽象出大小。然后,您使用抽象类型,这对于您想要支持的系统集来说是正确的。

One way I've seen it done is abstracting out the size with precompiler directives and typedefs. Then you use the abstracted types which will be correct for the set of systems you want to support.

蓦然回首 2024-08-29 12:03:58

也许您可以只对 sizeof(int) 使用断言,这样至少您将来是否违反了假设您就会知道。

Perhaps you could just use an assert on the sizeof(int) so that at least if your assumptions are violated in future you'll know.

Smile简单爱 2024-08-29 12:03:58

到目前为止,最简单的解决方案是将 char* 转换为 char[4]。在每个平台上,char[4] 都是一个 4 字节对象。对于整个波形,您可能需要 char[4*512]

By far the easiest solution is to get a char* to a char[4]. On each and every platform, char[4] is a 4-byte object. For a entire waveform, you might need a char[4*512]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文