I'm trying to send an NSMutableArray, or even just two strings to a function in C++ from Objective-C without success. I have no issues getting a string from C++ back to Objective-C, it's the other way around where I'm confused. Here's my code for getting a string from 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?
*(new HelloTest). Hold the pointer instead.*(new HelloTest)is a memory leak in C++, and I'm assuming Objective-C++ doesn't have any special rules here. It allocates aHelloTestobject on the heap, then copies it to thehelloTestproperty, then forgets about the heap allocated object