简体   繁体   English

我需要在 Swift 中 memset 一个 C 结构吗?

[英]Do I need to memset a C struct in Swift?

AFAIK, In swift, calling the default initialiser of classes/structs will initialise everything to 0 , nil . AFAIK,在 swift 中,调用类/结构的默认初始化程序会将所有内容初始化为0nil In C (socket programming for example) sometimes memset is used to set everything to 0 before using the struct.在 C(例如套接字编程)中,有时在使用结构体之前使用 memset 将所有内容设置为 0。 Do I need to use memset in swift too or is fine the way I wrote it?我是否也需要在 swift 中使用 memset 还是我写的方式很好?

(BTW, In this case memset is used because hints should be set to 0 except below 2 parameters. Non 0 (garbage, etc) will have side effects on res when calling getaddrinfo . (顺便说一句,在这种情况下,使用memset是因为除以下 2 个参数外, hints应设置为 0。非 0(垃圾等)将在调用getaddrinfo时对res产生副作用。

C: C:

struct addrinfo hints, *res;
int status;

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;

status = getaddrinfo(NULL, MYPORT, &hints, &res);

Swift:迅速:

var res = UnsafeMutablePointer<addrinfo>()
var hints = addrinfo()
hints.ai_family = AF_UNSPEC
hints.ai_socktype = SOCK_STREAM

let status = getaddrinfo(nil, MYPORT, &hints, &res)

From the Xcode 6.3 release notes :来自Xcode 6.3 发行说明

Imported C structs now have a default initializer in Swift that initializes all of the struct's fields to zero.导入的 C 结构现在在 Swift 中有一个默认初始化器,可以将结构的所有字段初始化为零。

which means that意思就是

var hints = addrinfo()

initializes all fields of struct addrinfo to zero and there is no need to call memset() .struct addrinfo所有字段初始化为零,无需调用memset()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM