ctfd
ctfd

Reputation: 348

How to send an array to C++ function from Objective-C

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?

Upvotes: 2

Views: 600

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

As per my comment, hold the pointer to the C++ class:

@interface WrapperClass ()
@property (nonatomic) HelloTest* helloTest;
@end

Better still consider using std::unique_ptr<HelloTest> to manage the memory.

Add the set method in the C++ class (implementation omitted):

namespace test {
    class HelloTest {
    public:
        std::string getHelloString() const;    // Add const!
        void setHelloStrings(const std::array<std::string>& strings);
    };
}

and pass it like this from 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);
}

Upvotes: 2

Related Questions