我正在开发POSIX C++程序的Windows端口.
问题是标准POSIX函数如accept()或bind()期望'int'作为第一个参数,而其WinSock对应物使用'SOCKET'.
当编译为32位时一切都很好,因为两者都是32位,但在Win64下SOCKET是64位,int仍然是32位,它产生了很多编译器警告,如下所示:
warning C4244: '=' : conversion from 'SOCKET' to 'int', possible loss of data
我尝试使用typedef来解决这个问题:
#ifdef _WIN32
typedef SOCKET sock_t;
#else
typedef int sock_t;
#endif
Run Code Online (Sandbox Code Playgroud)
并在适当的位置用'sock_t替换'int'.
在我到达调用OpenSSL API的代码的一部分之前,这很好.
事实证明,OpenSSL甚至在Win64上也使用了套接字.这看起来很奇怪,所以我开始寻找答案,但我发现的唯一一件事是在openssl-dev邮件列表上的一个旧帖子,它引用了一条评论e_os.h:
/*
* Even though sizeof(SOCKET) is 8, it's safe to cast it to int, because
* the value constitutes an index in per-process table of limited size
* and not a real pointer.
*/
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
将SOCKET转换为int是否真的安全?
我想看一些证明SOCKET值不能大于2 ^ 32的文档.
提前致谢!
Ryck