我目前正在尝试为 C 库创建一个 Swift 包装器。为此,我使用 Swift 包管理器。
我的计划是创建一个 system-module
第一个包含所需的 C 库。之后,该库将包含在另一个类型为 Library
的 Swift 包中。 。为了测试一切,我想制作另一个类型为 executable
的 Swift 包。
问题出在最后一部分。可执行文件找不到对 Library
的引用.
为了更好地解释一切,这是我的工作流程:
1)
创建一个新的 swift 包:swift package init --type system-module
。
这是最终的Package.swift
文件:
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Clibmongoc",
pkgConfig: "libmongoc-1.0",
providers: [
.brew(["mongo-c-driver"])
],
products: [
.library(name: "Clibmongoc", targets: ["Clibmongoc"])
]
)
还有.modulemap
:
module Clibmongoc [system] {
header "/usr/local/include/libmongoc-1.0/mongoc.h"
link "Clibmongoc"
export *
}
2)
现在我必须创建 Library
:
首先我用: swift package init --type Library
初始化它。生成的 Package.swift 是:
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "SwiftLibMongoC",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "SwiftLibMongoC",
targets: ["SwiftLibMongoC"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "../Clibmongoc", from: "1.0.2")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftLibMongoC",
dependencies: ["Clibmongoc"]),
.testTarget(
name: "SwiftLibMongoCTests",
dependencies: ["SwiftLibMongoC"]),
]
)
所以基本上我只是将之前新创建的包复制到新库中。我还确定了 system-module
的 git 标签设置为1.0.2
。我还确保将依赖项包含在目标中。正如创建 .xcodeproj
时所预期的那样我可以访问Clibmongoc
system-module
.
现在我们解决问题了。
3) 我使用 swift package init --type executable
创建了测试模块我包括了新创建的 Library
进入 list :
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "SwiftLibMongoCTest",
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "../SwiftLibMongoC", from: "0.0.2")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftLibMongoCTest",
dependencies: ["SwiftLibMongoC"]),
.testTarget(
name: "SwiftLibMongoCTestTests",
dependencies: ["SwiftLibMongoCTest"]),
]
)
我再次确保 git 标记的版本已正确设置为 0.0.2
还有依赖项 SwiftLibMongoC
已设置为目标中的依赖项。
当尝试构建可执行文件时它可以工作,但是当 .xcodeproj
正在创建,我可以导入 system-module
Clibmongoc
但我没有得到 auto completion
对于新的Library
SwiftLibMongoC
。但是,如果我导入它并构建它,那么如果我尝试从 Library
访问默认生成的代码,我不会收到错误。在新executable
我收到错误:
use of unresolved identifier
非常感谢任何帮助。
最佳答案
这实际上是一个非常愚蠢的错误。 swift 的默认访问级别是内部的,这意味着您无法从模块外部看到代码。我从未真正查看过预先生成的代码,因此我从未想过我必须将默认结构更改为公共(public)。
我希望将来这个问题能在文档中得到更好的解决。
关于未包含 SwiftPM 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53994956/