Making a Objective-C Wrapper for a C++ Library

后端 未结 3 478
囚心锁ツ
囚心锁ツ 2020-12-29 15:42

I am trying to make a wrapper in Objective-C so I don\'t have to write c++ outside the library classes.

The Library main file is LLAHProcessor.h .cpp

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 16:05

    All you need to do is to create a .mm as you have done, and the compiler should take care of everything.

    The caveat being that it is not safe to have anything C++ related in the .h files, since they can/will be imported by other Objective-C only files, and then everything breaks down. The main problem here is that you can not define C++ types directly as instance variables for your Objective-C wrapper class, unless every single .m file is renamed as a Objective-C++ .mm file.

    The solution is to define the instance variables as void* in the header file, and access them with type casting from the implementation file. Easiest solution for this would be to access the instance variable using a private property that to the typecast for you.

    Example code assuming Foo is a C++ class defined in Foo.h:

    // FooWrapper.h
    #import 
    
    @interface FooWrapper : NSObject {
    @private
      void* foo;
    }
    // Actual wrapper API for Foo…
    @end
    
    
    // FooWrapper.mm
    #import "FooWrapper.h"
    #include 
    #include "Foo.h"
    
    @interface FooWrapper ()
    @property(nonatomic, assign) Foo* foo;
    @end
    
    @implementation FooWrapper
    -(Foo*)foo {
      return (Foo*)foo;
    }
    -(void)setFoo:(Foo*)aFoo {
      foo = (void*)aFoo;
    }
    // Implementation of actual API for Foo…
    @end
    

提交回复
热议问题