[英]Include C++ header file in Swift
我有一個C ++頭文件(名為header.h
),我想將其包含在我的Swift項目中。
由於我想要包含的C ++框架尚未完成,我現在只有頭文件。
我的C ++頭文件header.h
看起來有點像這樣:
#include <vector>
struct someStruct{
float someAttr;
}
class someClass{
public:
enum SomeEnum{
Option1,
Option2
}
void someFunc(const double value) {}
}
問題是,當我嘗試在project-Bridging-Header.h
包含header.h
文件時,它永遠不會找到我在header.h中包含的向量
我嘗試將header.h
重命名為header.hpp
。 我嘗試在右側面板中將橋接標題類型設置為C ++標題。 但他們都沒有幫助。
我希望你們中的一些人可以幫助我弄清楚我做錯了什么。
不幸的是,不能直接在Swift中使用C ++類,請參閱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
擴展名。 您可以使用.m
創建Objective-C文件,然后重命名它。
#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 ++類的實例支持。
這只是一個簡單的例子,可以給你一個想法。 如果你遇到其他問題,他們可能應該得到單獨的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.