How to convert const char* to KString in Kotlin/Native?

橙三吉。 提交于 2019-12-13 16:25:46

问题


In a C++ file, I want to convert a const char* to KString, so that I can then pass the KString to a Kotlin file using Kotlin/Native.

I believe the answer lies in the function

    OBJ_GETTER(utf8ToUtf16, const char* rawString, size_t rawStringLength)

that I found in KString.cpp. But even though I discovered the used define statements in Memory.h, I have not yet managed to properly call the function utf8ToUtf16 from my own C++ file to get a KString. Any help is appreciated.


回答1:


It depends on how you want to interact with Kotlin code. If you produce dynamic library with -produce dynamic, then string are converted automatically, see for example https://github.com/JetBrains/kotlin-native/blob/adf8614889e8cf5038a79960aa9651ca7d45e409/samples/python_extension/src/main/c/kotlin_bridge.c#L72. So no additional magic is required at all. Same with Objective-C strings and -produce framework. And for other cases, there shall be no need to pass strings C -> Kotlin (callbacks produced with staticCFunction also do autoconversion).




回答2:


I ended up taking the pieces to write my own function:

KString getKString(const char* rawString) {
    size_t rawStringLength = strlen(rawString);
    ObjHeader** OBJ_RESULT;
    uint32_t charCount = utf8::unchecked::distance(rawString, rawString + rawStringLength);
    ArrayHeader* result = AllocArrayInstance(theStringTypeInfo, charCount, OBJ_RESULT)->array();
    KChar* rawResult = CharArrayAddressOfElementAt(result, 0);
    auto convertResult =
    utf8::unchecked::utf8to16(rawString, rawString + rawStringLength, rawResult);
    ObjHeader* obj = result->obj();
    UpdateReturnRef(OBJ_RESULT, obj);
    return (const ArrayHeader*)obj;
}

In my test code (C++), I use it like this:

...
RuntimeState* state = InitRuntime();
KString inMessage;
{
    ObjHolder args;
    inMessage = getKString("Hello from C++");
}
...
DeinitRuntime(state);

and include Memory.h, Natives.h, Runtime.h, KString.h, utf8.h, stdlib.h, and string. You may be able to get rid of some of these.

As a side remark, you may realize how AllocArrayInstance is used in the function. It would be nice, if one simply could do the same thing for getting a KString, something like:

ObjHeader** OBJ_RESULT;
KString kstr = utf8ToUtf16(rawString, rawStringLength, OBJ_RESULT);

This did not work from my function, since utf8ToUtf16 was not found. I believe the reason is, that (at the time of writing) the respective function in KString.cpp is inside a namespace {...} block, such that it cannot be used from another file. That's why I ended up mimicking the function as shown above.



来源:https://stackoverflow.com/questions/47664501/how-to-convert-const-char-to-kstring-in-kotlin-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!