希望可以有人帮帮我。我正在尝试为 Swift 包管理器构建 swift 包。我想在其中包含一些 C++ 源代码,并利用 OOP 的所有优点对其进行操作。所以我创建了新包并添加了三个模块:一个用于在包中快速执行(“swift-exec”),第二个用于我的 c++ lib(“cppLib”),第三个用于 c++ lib(“cwrapper”)的objective-c包装器.
包装说明:
import PackageDescription
let package = Package(
name: "Objc",
targets: [Target(name: "cwrapper", dependencies:["cpplib"]),
Target(name: "swift-exec", dependencies:["cwrapper"]),
]
)
我的 C++ 库:
cpplib.cpp:
#import "include/cpplib.h"
A::A(int _i) : m_Int(_i) {}
int A::getInt() { return m_Int ; }
cpplib.h:
class A {
public:
A(int);
int getInt();
private:
int m_Int;
};
我的包装:
包装器.h
#import <Foundation/Foundation.h>
@interface Wrapper : NSObject
-(instancetype)initWithNum:(NSInteger)num;
- (NSInteger)getIntFromObject;
@end
包装器。毫米
#import "include/cwrapper.h"
#import "cpplib.h"
@interface Wrapper()
@property (nonatomic, readonly) A* internal;
@end
@implementation Wrapper
-(instancetype)initWithNum:(NSInteger) num {
self = [super init];
if (self != nil) {
_internal = new A((int)num);
}
return self;
}
- (NSInteger)getIntFromObject {
return (NSInteger)self.internal->getInt();
}
- (void)dealloc {
delete _internal;
}
@end
我的迅速执行:
main.swift :
import cwrapper
let object = Wrapper.init(num: 54)
guard let object = object else {
exit(-1)
}
print("\(object.getIntFromObject())")
当我在 Xcode 中构建我的项目时,我没有错误,我的项目成功构建、链接和运行。但是当我尝试使用命令“ swift build ”构建包时,出现错误:
$ swift build
Linking cwrapper
Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_NSObject", referenced from:
_OBJC_CLASS_$_Wrapper in cwrapper.mm.o
"_OBJC_METACLASS_$_NSObject", referenced from:
_OBJC_METACLASS_$_Wrapper in cwrapper.mm.o
"__objc_empty_cache", referenced from:
_OBJC_CLASS_$_Wrapper in cwrapper.mm.o
_OBJC_METACLASS_$_Wrapper in cwrapper.mm.o
"_objc_msgSend", referenced from:
-[Wrapper getIntFromObject] in cwrapper.mm.o
"_objc_msgSendSuper2", referenced from:
-[Wrapper initWithNum:] in cwrapper.mm.o
-[Wrapper dealloc] in cwrapper.mm.o
"_objc_retain", referenced from:
-[Wrapper initWithNum:] in cwrapper.mm.o
"_objc_storeStrong", referenced from:
-[Wrapper initWithNum:] in cwrapper.mm.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
<unknown>:0: error: build had 1 command failures
error: exit(1): /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /path/to/DEV/playground/swpackage/.build/debug.yaml
所以我的问题是:有可能做我想做的事吗?将 c++ 包装到 objc 并将其链接到 swift 包?
如果是,我做错了什么?
更新:经过一些研究,我发现当 Xcode 尝试链接 .mm 文件时,它使用命令
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++
但是当我尝试在控制台中执行此操作时,“swift build”会使用它:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang