In my iOS project, I want to call a C++ function from my Swift code that takes an object from my Swift code and returns another object.
So far, following this tutorial and adding a little bit more stuff, I managed to call a C++ function that takes a simple parameter and returns a string:
- I create the
NativeLibWrapper.hfile:
#import <Foundation/Foundation.h>
@interface NativeLibWrapper : NSObject
- (NSString *) sayHello: (bool) boolTest;
@end
- I create the
NativeLibWrapper.mmfile:
#import <Foundation/Foundation.h>
#import "NativeLibWrapper.h"
#import "NativeLib.hpp"
@implementation NativeLibWrapper
- (NSString *) sayHello: (bool) boolTest {
NativeLib nativeLib;
std::string retour = nativeLib.sayHello(boolTest);
return [NSString stringWithCString: retour.c_str() encoding: NSUTF8StringEncoding];
}
@end
- I create the
NativeLib.hppfile:
#ifndef NativeLib_hpp
#define NativeLib_hpp
#include <stdio.h>
#include <string>
class NativeLib
{
public:
std::string sayHello(bool boolTest);
};
#endif /* NativeLib_hpp */
- I create the
NativeLib.cppfile:
#include "NativeLib.hpp"
std::string NativeLib::sayHello(bool boolTest)
{
return "Hello C++ : " + std::to_string(boolTest);
}
- I add the following in
Runner/Runner/Runner-Bridging-Header.h:
#import "NativeLibWrapper.h"
- And finally, I call the C++ function in Swift:
NativeLibWrapper().sayHello(true)
But now, let's say that my C++ sayHello() function takes this kind of object as a parameter (so I can access it in the C++ function):
class TestAPOJO {
var value1 = ""
var value2 = false
}
and returns this kind of object (generated from the C++ function but then mapped into a Swift object, or something like that):
class TestBPOJO {
var value3 = 0.0
var value4 = false
}
How can I achieve that?
Thanks.