在POSIX不符合要求的系统上替代ssize_t [英] Alternative to ssize_t on POSIX-unconformant systems
问题描述
我正在编写一个涉及网络I/O的程序,因此使用send
和recv
,它们是POSIX函数.它们返回一个ssize_t
,它也是POSIX特定的.
包装器看起来像这样的ATM:
I'm writing a program involving network I/O, so send
and recv
are used, which are POSIX functions. They return a ssize_t
, which is POSIX-specific too.
The wrappers look like this ATM:
ssize_t sock_send(int sock, const void* msg, size_t len) {
return send(sock, msg, len, 0);
}
即使我在当前的实现中严重依赖POSIX,我还是希望使接口与标准紧密结合,因为我计划稍后再编写Windows实现,而POSIX不一定可用(该死,Windows). !).
Even though I'm heavily depending on POSIX in my current implementation, I want to make the interface stick closely to the standard because I am planning on writing a Windows implementation later, where POSIX isn't necessarily available (dammit, Windows!).
按照C11标准的规定,什么可以很好地替代ssize_t
?也许ptrdiff_t
?
还是应该以其他方式解决这个问题?
What would be a good substitution for ssize_t
as specified by the C11 standard? Perhaps ptrdiff_t
?
Or how should I approach this issue otherwise?
推荐答案
如果未定义类型ssize_t
,则可以自己定义.它应该是signed
类型,其大小与size_t
相同.从技术上讲,类型ptrdiff_t
不应小于size_t
,但可以更大以适应更大的范围.
If the type ssize_t
is not defined, you can just define it yourself. It is supposed to be a signed
type with the same size as size_t
. Technically, the type ptrdiff_t
should not be smaller than size_t
, but it could be larger to accommodate for the larger range.
这里是一种可移植的定义方式:
Here is a portable way to define it:
#include <limits.h>
#include <stddef.h>
#if SIZE_MAX == UINT_MAX
typedef int ssize_t; /* common 32 bit case */
#elif SIZE_MAX == ULONG_MAX
typedef long ssize_t; /* linux 64 bits */
#elif SIZE_MAX == ULLONG_MAX
typedef long long ssize_t; /* windows 64 bits */
#elif SIZE_MAX == USHRT_MAX
typedef short ssize_t; /* is this even possible? */
#else
#error platform has exotic SIZE_MAX
#endif
这篇关于在POSIX不符合要求的系统上替代ssize_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!