gpt4 book ai didi

swift - 字符串传输

转载 作者:行者123 更新时间:2023-11-30 11:38:28 26 4
gpt4 key购买 nike

我想使用以下代码将 String 返回给 Swift:

MyFile.h:

+ (char *) myCoolCode;

MyFile.mm:

+(string)myCoolCode {
string myCoolString = "";
myCoolString += "123";
return myCoolString;
}

MyFile.swift:

let superCoolString = MyBridge.myCoolCode()
print(superCoolString)

但显然它似乎没有以正确的方式工作,因为它在内部深处的某个地方崩溃了。

See this image

最佳答案

正如其他人已经在评论中指出的那样,您应该将 .mm 文件的返回类型修复为 char * 而不是 string 。您应该始终保持这两种类型相同。您的函数实现的示例可以是:

- (char *)myCoolCode
{
char str[] = "foobar";
//You can do whatever you want with str here. Just make sure it's null terminated
return str;
}

然后在你的快速代码中:

let myCoolString = String(cString: MyBridge.myCoolCode())
print(myCoolString)

字符串构造函数的引用是 here.

您的代码崩溃的原因可能是因为您返回了一个在 Swift 中不起作用的 std::string 实例。您可以使用 std::string 但返回时必须将其转换为 char *。您可以按原样这样做shown here.

关于swift - 字符串传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49475041/

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