【发布时间】:2014-08-11 15:06:48
【问题描述】:
我有一个具有
的 Objective-C 类#include <arpa/inet.h>
但是如何在 Swift 语言中包含这个呢?
【问题讨论】:
标签: ios objective-c swift
我有一个具有
的 Objective-C 类#include <arpa/inet.h>
但是如何在 Swift 语言中包含这个呢?
【问题讨论】:
标签: ios objective-c swift
您不能在 Swift 源代码文件中直接包含 C 标头。而是在 Objective C 头文件中包含 C 头文件,并在 Xcode 项目中添加一个包含所有需要的 Objective C 头文件的桥接头。
【讨论】:
如果您导入Foundation 或Darwin,则<arpa/inet.h> 中定义的一些函数可用。
但是,了解如何使用它们需要一些工作。您应该创建一个游乐场或使用命令行 REPL 进行试验。示例:
$ xcrun swift
"crashlog" and "save_crashlog" command installed, use the "--help" option for detailed help
"malloc_info", "ptr_refs", "cstr_refs", and "objc_refs" commands have been installed, use the "--help" options on these commands for detailed help.
Welcome to Swift! Type :help for assistance.
1> import Foundation
2> inet_addr("10.0.1.1")
$R6: in_addr_t = {
value = 16842762
}
3> var a = in_addr(s_addr: 16842762)
a: in_addr = {
s_addr = {
value = 16842762
}
}
4> inet_netof(a)
$R7: in_addr_t = {
value = 10
}
5>
您可能会发现处理 C 字符串的函数(如 inet_ntoa)太难使用了。您可能更容易在 Objective-C 中编写一个包装类,为您感兴趣的每个 <arpa/inet.h> 函数提供一个类方法。类方法可以在原始 C 字符串和 NSStrings 之间进行转换。然后你可以从你的 Swift 代码中调用这个 Objective-C 包装器的类方法。
【讨论】: