Skip to content

Instantly share code, notes, and snippets.

@krystofwoldrich
Last active December 3, 2023 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krystofwoldrich/880cf576ba008a196aa3c6f75e3d3b9a to your computer and use it in GitHub Desktop.
Save krystofwoldrich/880cf576ba008a196aa3c6f75e3d3b9a to your computer and use it in GitHub Desktop.
How to use RN JSI to convert String to UTF8 Bytes (iOS)
// 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