不幸的是,不可能直接在 Swift 中使用 C++ 类,请参阅https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216-CH2-ID0 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216-CH2-ID0:
您无法将 C++ 代码直接导入到 Swift 中。相反,创建一个
C++ 代码的 Objective-C 或 C 包装器。
实际上,封装 C++ 以在 Swift 中使用的一种便捷方法是 Objective-C++。 Objective-C++ 源文件可以混合包含 Objective-C 和 C++ 代码。这是基于您问题中的代码片段的快速部分示例。仅有的someClass
部分包裹在这里。在生产代码中,您还需要考虑内存管理。
包装器的头文件,mywrapper.h
,没有 C++ 的痕迹:
#ifndef mywrapper_h
#define mywrapper_h
#import <Foundation/Foundation.h>
// This is a wrapper Objective-C++ class around the C++ class
@interface someClass_oc : NSObject
-(void)someFunc:(double)value;
@end
#endif /* mywrapper_h */
这是 Objective-C++ 的实现,mywrapper.mm
。请注意.mm
扩大。您可以使用以下内容创建 Objective-C 文件.m
然后重命名它。
#import "mywrapper.h"
#import "header.h" // CAN import a C++ header here, in Objective-C++ code
// Use an extension on someClass_oc because we need to use someClass,
// but we couldn't do it in mywrapper.h,
// which is visible from Swift and thus can't contain C++ stuff.
@interface someClass_oc ()
{
someClass * ptrSomeClass;
}
@end
@implementation someClass_oc
-(id)init
{
// In this example ptrSomeClass is leaked...
ptrSomeClass = new someClass();
return self;
}
-(void)someFunc:(double)value
{
ptrSomeClass->someFunc(value);
}
@end
现在您可以导入mywrapper.h
在桥接标头中,然后在 Swift 中执行类似的操作:
let x = someClass_oc()
x.someFunc(123.456)
因此,您可以在 Swift 中创建一个对象,该对象由 C++ 类的实例支持。
这只是一个简单的例子,旨在为您提供一个想法。如果您遇到其他问题,他们可能需要单独提问。