如何在不同的机器上保持C变量类型的固定大小? [英] How to maintain fixed size of C variable types over different machines?

查看:82
本文介绍了如何在不同的机器上保持C变量类型的固定大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直都这样的功能。

I've all this kind of functions.

ssize_t fuc1(int var1, void *buf, size_t count);
int func2(char *charPtr, int mode, int dev);
short func3( long var2);

问题是,在不同的机器(64&安培; 32位)编译时的C数据类型有不同的尺寸。这甚至无效是真的*。对于一些的原因。我需要确保这些尺寸都是每台机器(64&安培; 32位)上的相同。所以,我应该怎么修改这些?

problem is that data types in C has different sizes when compiled on different machines(64bit & 32bit). This is true for even void*. For some reasons. I need to ensure that these sizes all are same on every machine(64bit & 32bit). So, how should I modify these ?

推荐答案

使用C99,< stdint.h> int32_t 等类型。 维基百科的更多细节。

Use C99, <stdint.h>, and int32_t etc types. More details on Wikipedia.

有没有办法来为指针类型做到这一点,因为他们是根据定义,特定于平台的。有在其中你可能需要它们是一致的,因为他们不是序列没有有效的用例。如果你用一个指针变量来存储指针的的其它数据(例如,取决于一些标志),使用一些确切的整数类型的联合与指针类型。另外,使用C99 uintptr_t形式,投当你需要把它当作这样的指针。

There's no way to do this for pointer types, because they are, by definition, platform-specific. There is no valid use case in which you could possibly need them to be consistent, because they are not serializable. If you use a pointer variable to store pointer and other data (e.g. depending on some flag), use a union of some exact integral type with a pointer type. Alternatively, use C99 uintptr_t, and cast to pointer when you need to treat it as such.

这篇关于如何在不同的机器上保持C变量类型的固定大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆