我试图从Objective-C向C++中的函数发送一个NSMutableArray,甚至两个字符串,但没有成功。 从C++将一个字符串返回到Objective-C,我没有任何问题,但我感到困惑的是另一种方式。 下面是我从C++获取字符串的代码:
WrapperClass.h
#ifndef WrapperClass_hpp
#define WrapperClass_hpp
#include <stdio.h>
#include <stdlib.h>
@interface WrapperClass : NSObject
@end
@interface WrapperClass ()
- (NSString *)getHelloString;
- (NSMutableArray *)sendInfo :(NSString *)str1 :(NSString *)str2;
// the array above is what I want to send to C++
@end
#endif /* WrapperClass_h */
WrapperClass.mm
#import <Foundation/Foundation.h>
#import "WrapperClass.h"
#include "WrapperClass.h"
#include "CppClass.h"
using namespace test;
@interface WrapperClass ()
@property (nonatomic) HelloTest helloTest;
@end
@implementation WrapperClass
- (NSString *)getHelloString {
self.helloTest = *(new HelloTest);
std::string str = self.helloTest.getHelloString();
NSString* result = [[NSString alloc] initWithUTF8String:str.c_str()];
return result;
}
- (NSMutableArray *)sendInfo :(NSString *)str1 :(NSString *)str2 {
std::string str1 = std::string([str1 UTF8String]);
std::string str1 = std::string([str2 UTF8String]);
std::array<std::string, 2> myArray = {{ str1, str2 }};
// Not sure how to send to CPP ...
}
cppclass.h
#ifndef Cpp_Class_h
#define Cpp_Class_h
#include <stdio.h>
#include <string>
#include <array>
using namespace std;
namespace test {
class HelloTest {
public:
std::string getHelloString();
};
}
#endif
cppClass.cpp
std::string test::HelloTest::getHelloString() {
std::string outString = "Hello World!";
return outString;
}
// this code gets the string from c++, but how to
// send two strings or an array to a function?
根据我的意见,保持指向C++类的指针:
@interface WrapperClass ()
@property (nonatomic) HelloTest* helloTest;
@end
最好还是考虑使用std::unique_ptr
来管理内存。
在C++类中添加set方法(省略实现):
namespace test {
class HelloTest {
public:
std::string getHelloString() const; // Add const!
void setHelloStrings(const std::array<std::string>& strings);
};
}
然后像这样从Objective-C++中传递它:
- (NSMutableArray *)sendInfo :(NSString *)str1 :(NSString *)str2 {
std::string str1 = std::string([str1 UTF8String]);
std::string str1 = std::string([str2 UTF8String]);
std::array<std::string, 2> myArray = {{ str1, str2 }};
self.helloTest->setHelloStrings(myArray);
}