xcode - 如何将字符串从原生 iOS 插件返回到 unity?

标签 xcode unity-game-engine

我正在创建一个 iOS 插件,它需要向 Unity 返回一个字符串(或 const char*)。我该如何实现它?

最佳答案

我想澄清一下之前的答案。 C# 声明:

[DllImport("__Internal")]
private static extern string getString();

从 objc 返回一个字符串与 @Cabrra 所说的完全一样:

char* convertNSStringToCString(const NSString* nsString)
{
    if (nsString == NULL)
        return NULL;

    const char* nsStringUtf8 = [nsString UTF8String];
    //create a null terminated C string on the heap so that our string's memory isn't wiped out right after method's return
    char* cString = (char*)malloc(strlen(nsStringUtf8) + 1);
    strcpy(cString, nsStringUtf8);

    return cString;
}

extern "C" char* getString()
{
    const NSString* str = @"string";
    return convertNSStringToCString(str);
}

虽然有人提到这种方式会导致内存泄漏,但其实并不对。这种方式在Unity中工作得很好,没有发生泄漏(我测试了很多次)。 Unity clearly states那个

String values returned from a native method should be UTF–8 encoded and allocated on the heap. Mono marshalling calls free for strings like this.

关于xcode - 如何将字符串从原生 iOS 插件返回到 unity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37047781/

相关文章:

c# - Unity C# 嵌套 IEnumerator

user-interface - 在 Unity 中从像素坐标转换为 UI 坐标

ios - 新语言键盘 iOS

c++ - Xcode 5.1 针对 C++98 编译,避免 C++11 特性

ios - Xcode 6 大小类

c# - Php 转 Unity Json/数组 返回 null

c# - 即使我检查碰撞,球体还是重叠的

c++ - 如何将 lua 脚本语言包含到 C++ XCode 中?

ios - Flutter 将 com.apple.security.network.client 添加到 *.entitlements

c# - 最快的 Sprite 设置(2D 和 UI)