search

Home  >  Q&A  >  body text

objective-c - oc, c++混编,c++函数中如何识别self?

一个项目,用到了opencv库,有一个代理方法,这里假设为void cPlusPlusMethod(),在这个函数中要调用[self test1];但是在这个函数中无法识别self.如何解决?
以下是代码:

#import "ViewController.h"
#include <fstream>

using namespace std;
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

 
}
void cPlusPlusMethod() {
    //在C++这个代理方法中 ,要运行 用oc写的类方法:[self test1];
    [self test1];//不识别self如何解决?
}
- (void) test1 {
    NSLog(@"test1 ");
}

@end

伊谢尔伦伊谢尔伦2772 days ago461

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:22:52

    That is not called a proxy method, it should be called a callback function.

    C functions are placed in the code area of ​​​​the memory when running, so if you want to access OC objects, you need to pass parameters or access global variables.

    #import "ViewController.h"
    #include <fstream>
    
    using namespace std;
    static ViewController *handle;
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        handle = self;
    }
    
    void cPlusPlusMethod() {
        [handle test1];
    }
    
    - (void)test1 {
        NSLog(@"test1 ");
    }
    
    - (void)dealloc {
        handle = NULL;
    }
    
    @end

    reply
    0
  • Cancelreply