2010-02-14 108 views
17

我正在嘗試混合使用C++和Objective-C,我已經做了大部分的工作,但希望在Objective-C和C++代碼之間有一個接口類。因此我想在ViewController接口中有一個持久的C++對象。將C++對象添加到Objective-C類

這失敗時,沒有禁止型「myCppFile」的聲明:

#import <UIKit/UIKit.h> 
#import "GLView.h" 
#import "myCppFile.h" 

@interface GLViewController : UIViewController <GLViewDelegate> 
{ 
    myCppFile cppobject; 
} 

@end 

然而,這只是正常的.mm實現文件(它不工作,因爲我想cppobject來調用之間仍然存在)

#import "myCppFile.h" 
@implementation GLViewController 
- (void)drawView:(UIView *)theView 
{ 
    myCppFile cppobject; 
    cppobject.draw(); 
} 

回答

27

您應該使用opaque pointers,僅包括C++實現您的Objective-C類的文件中的頭文件。這樣,你不要強迫其他文件,其中包括使用Objective-C的頭++:

// header: 
#import <UIKit/UIKit.h> 
#import "GLView.h" 

struct Opaque; 

@interface GLViewController : UIViewController <GLViewDelegate> 
{ 
    struct Opaque* opaque; 
} 
// ... 
@end 

// source file: 
#import "myCppFile.h" 

struct Opaque { 
    myCppFile cppobject; 
}; 

@implementation GLViewController 
// ... create opaque member on initialization 

- (void)foo 
{ 
    opaque->cppobject.doSomething(); 
} 
@end 
+0

謝謝,其他建議似乎並沒有工作,我最終宣佈我的對象爲「id *」,然後將它轉換爲我想要使用它的任何地方的正確類型。這似乎是一樣的想法,但是因爲我不必做所有額外的演員,所以更清潔。 – Winder 2010-02-14 20:33:05

+2

我總是更喜歡不透明的指針,而不是更多的工作,但是您可以重新獲得完整的安全類型。 – 2010-02-14 20:41:11

+0

我一直在玩這個不透明的指針,這個指針我廣泛用於C/C++包裝,但到目前爲止我還沒有看到真正的好處。你能比較這種風格(以及一些代碼顯示「不透明」是如何分配和釋放的)這裏基於void *的風格:http://robnapier.net/blog/wrapping-c-objc-20 – 2010-02-20 16:44:21

0

我認爲你需要設置以下標誌true在您的項目設置:

​​

這應該允許您在Objective-C類中實例化C++對象。

+0

這似乎並沒有工作。我正在使用Xcode 3.2.1和3.0 iphone SDK。 – Winder 2010-02-14 18:29:19

3

確保包含GLViewController.h的所有文件都是Objective-C++源文件(* .mm)。

如果包括C++代碼在您的視圖控制器的標題,所有導入這個頭必須能夠了解它的來源,所以他們必須在Objective-C++

2

您需要聲明C++對象在你.mm文件中的接口塊。

在.mm:

#include "SomeCPPclass.h" 

@interface SomeDetailViewController() { 
    SomeCPPclass* _ipcamera; 
} 
@property (strong, nonatomic) UIPopoverController *masterPopoverController; 
- (void)blabla; 
@end 
+0

請注意() - 這是使這項工作的黑色(et)魔術:) – goelectric 2014-03-27 18:09:34