gpt4 book ai didi

c++ - 如何将数组从 Objective-C 发送到 C++ 函数

转载 作者:行者123 更新时间:2023-12-02 10:00:28 25 4
gpt4 key购买 nike

我正在尝试从 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<HelloTest>来管理内存。
在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);
}

关于c++ - 如何将数组从 Objective-C 发送到 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62776585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com