Last active
December 3, 2023 21:54
-
-
Save krystofwoldrich/880cf576ba008a196aa3c6f75e3d3b9a to your computer and use it in GitHub Desktop.
How to use RN JSI to convert String to UTF8 Bytes (iOS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspired by https://ospfranco.com/post/2021/02/24/how-to-create-a-javascript-jsi-module/ | |
struct MuttableStringBuffer : facebook::jsi::MutableBuffer { | |
MuttableStringBuffer(std::string s) : _s(std::move(s)) {} | |
size_t size() const override { | |
return _s.length(); | |
} | |
uint8_t *data() override { | |
return reinterpret_cast<uint8_t *>(_s.data()); | |
} | |
std::string _s; | |
}; | |
auto stringToUTF8Bytes = jsi::Function::createFromHostFunction( | |
runtime, // JSI runtime instance | |
jsi::PropNameID::forAscii(runtime, "stringToUTF8Bytes"), // Internal function name | |
1, | |
[](jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* arguments, size_t count) -> jsi::Value { | |
if (!arguments[0].isString()) { | |
throw jsi::JSError(runtime, "Expected the first and only argument to be a String."); | |
} | |
std::string s = arguments[0].asString(runtime).utf8(runtime); | |
std::shared_ptr<MuttableStringBuffer> shared = std::make_shared<MuttableStringBuffer>(s); | |
return jsi::Value(jsi::ArrayBuffer(runtime, std::move(shared))); | |
} | |
); | |
runtime.global().setProperty(runtime, "stringToUTF8Bytes", std::move(stringToUTF8Bytes)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment