加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xcode – 如何将字符串从本机iOS插件返回到统一?

发布时间:2020-12-14 19:20:09 所属栏目:百科 来源:网络整理
导读:我正在创建一个iOS插件,需要将一个字符串(或const char *)返回给Unity.我该如何实现它? 解决方法 extern "C"{ int _pow2(int x) { // Just a simple example of returning an int value return x * x; } // Returns a char* (a string to Unity) char* _hel
我正在创建一个iOS插件,需要将一个字符串(或const char *)返回给Unity.我该如何实现它?

解决方法

extern "C"
{
    int _pow2(int x)
    {
        // Just a simple example of returning an int value
        return x * x;
    }

    // Returns a char* (a string to Unity)
    char* _helloWorldString()
    {
        // We can use NSString and go to the c string that Unity wants
        NSString *helloString = @"Hello World";
        // UTF8String method gets us a c string. Then we have to malloc a copy to give to Unity. I reuse a method below that makes it easy.
        return cStringCopy([helloString UTF8String]);
    }

    // Here is an example of getting a string from Unity
    char* _combineStrings(const char* cString1,const char* cString2)
    {
        // This shows we can create two NSStrings* from the c strings from Unity
        NSString *string1 = CreateNSString(cString1);
        NSString *string2 = CreateNSString(cString2);
        NSString *combinedString = [NSString stringWithFormat:@"%@ %@",string1,string2];
        // Same as before,have to go to a c string and then malloc a copy of it to give to Unity
        return cStringCopy([combinedString UTF8String]);
    }
}

//I also like to include these two convenience methods to convert between c string and NSString*. You need to return a copy of the c string so that Unity handles the memory and gets a valid value.

char* cStringCopy(const char* string)
{
    if (string == NULL)
        return NULL;

    char* res = (char*)malloc(strlen(string) + 1);
    strcpy(res,string);

    return res;
}

// This takes a char* you get from Unity and converts it to an NSString* to use in your objective c code. You can mix c++ and objective c all in the same file.
static NSString* CreateNSString(const char* string)
{
    if (string != NULL)
        return [NSString stringWithUTF8String:string];
    else
        return [NSString stringWithUTF8String:""];
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读