如何将对象 return 传递给从 iOS Swift 调用的 C++ 函数?

How to pass and return an object to a C++ function called from iOS Swift?

在我的 iOS 项目中,我想从我的 Swift 代码调用一个 C++ 函数,该函数从我的 Swift 代码和 returns 另一个对象中获取一个对象。

到目前为止,在 this tutorial 之后并添加了一些东西,我设法调用了一个 C++ 函数,该函数采用一个简单的参数和 returns 一个字符串:

#import <Foundation/Foundation.h>

@interface NativeLibWrapper : NSObject

- (NSString *) sayHello: (bool) boolTest;

@end

#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

#ifndef NativeLib_hpp
#define NativeLib_hpp

#include <stdio.h>
#include <string>

class NativeLib
{
public:
    std::string sayHello(bool boolTest);
};

#endif /* NativeLib_hpp */

#include "NativeLib.hpp"

std::string NativeLib::sayHello(bool boolTest)
{
    return "Hello C++ : " + std::to_string(boolTest);
}
#import "NativeLibWrapper.h"
NativeLibWrapper().sayHello(true)

但是现在,假设我的 C++ sayHello() 函数将这种对象作为参数(因此我可以在 C++ 函数中访问它):

class TestAPOJO {

    var value1 = ""
    var value2 = false
}

和returns这种对象(从C++函数生成,然后映射到Swift对象,或类似的东西):

class TestBPOJO {

    var value3 = 0.0
    var value4 = false
}

我怎样才能做到这一点?

谢谢。

好的,这就是我为让它工作所做的工作:

  • 创建 Objective-C TestAPOJOTestBPOJO 类:
// TestAPOJO.h:

#import <Foundation/Foundation.h>

@interface TestAPOJO : NSObject

@property NSString *value1;
@property bool value2;

@end


// TestAPOJO.mm:

#import "TestAPOJO"

@implementation TestAPOJO

@end
  • 创建 C++ TestAPOJOFromCTestBPOJOFromC 类:
// TestAPOJOFromC.hpp:

#ifndef TestAPOJOFromC_hpp
#define TestAPOJOFromC_hpp

class TestAPOJOFromC
{
public:
    TestAPOJOFromC();
    ~TestAPOJOFromC();
    
    std::string value1;
    bool value2;
};

#endif /* TestAPOJOFromC_hpp */


// TestBPOJOFromC.cpp:

#include "TestBPOJOFromC.hpp"

TestBPOJOFromC::TestBPOJOFromC()
{
    value1 = "";
    value2 = false;
}

TestBPOJOFromC::~TestBPOJOFromC() = default;

  • NativeLibWrapper.h文件中,添加:

- (TestBPOJO *) getTestPOJOS: (TestAPOJO *) testAPOJO;

  • NativeLibWrapper.mm文件中,添加:
- (TestBPOJO *) getTestPOJOS: (TestAPOJO *) testAPOJO {
    NativeLib nativeLib;
    TestAPOJOFromC *testAPOJOFromC = new TestAPOJOFromC();
    testAPOJOFromC->value1 = std::string([testAPOJO.value1 UTF8String]);
    testAPOJOFromC->value2 = testAPOJO.value2;
    TestBPOJOFromC * testBPOJOFromC = nativeLib.getTestPOJOS(testAPOJOFromC);

    TestBPOJO *testBPOJO = [TestBPOJO new];
    testBPOJO.value3 = testBPOJOFromC->value3;
    testBPOJO.value4 = testBPOJOFromC->value4;
    return testBPOJO;
}