Skip to content

Commit e09d924

Browse files
committed
feat: Add function support to JSIConverter
1 parent c30f97b commit e09d924

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

package/cpp/jsi/JSIConverter.h

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,15 @@ template <> struct JSIConverter<bool> {
7373
}
7474
};
7575

76+
template <> struct JSIConverter<std::string> {
77+
static std::string fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
78+
return arg.asString(runtime).utf8(runtime);
79+
}
80+
static jsi::Value toJSI(jsi::Runtime& runtime, const std::string& arg) {
81+
return jsi::String::createFromUtf8(runtime, arg);
82+
}
83+
};
84+
7685
template <typename TInner> struct JSIConverter<std::optional<TInner>> {
7786
static std::optional<TInner> fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
7887
if (arg.isUndefined() || arg.isNull()) {
@@ -90,13 +99,29 @@ template <typename TInner> struct JSIConverter<std::optional<TInner>> {
9099
}
91100
};
92101

93-
template <> struct JSIConverter<std::string> {
94-
static std::string fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
95-
return arg.asString(runtime).utf8(runtime);
96-
}
97-
static jsi::Value toJSI(jsi::Runtime& runtime, const std::string& arg) {
98-
return jsi::String::createFromUtf8(runtime, arg);
99-
}
102+
template <typename ReturnType, typename... Args>
103+
struct JSIConverter<std::function<ReturnType(Args...)>> {
104+
static std::function<ReturnType(Args...)> fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
105+
jsi::Function func = arg.asObject(runtime).asFunction(runtime);
106+
return [&runtime, func = std::move(func)] (Args... args) -> ReturnType {
107+
func.call(runtime, JSIConverter::toJSI(args...));
108+
};
109+
}
110+
111+
template<size_t... Is>
112+
static jsi::Value callFunction(std::function<ReturnType(Args...)> function, jsi::Runtime& runtime, const jsi::Value* args, std::index_sequence<Is...>) {
113+
ReturnType result = function(JSIConverter<Args>::fromJSI(runtime, args[Is])...);
114+
return JSIConverter<ReturnType>::toJSI(runtime, result);
115+
}
116+
117+
static jsi::Value toJSI(jsi::Runtime& runtime, std::function<ReturnType(Args...)> function) {
118+
jsi::HostFunctionType jsFunction = [function = std::move(function)] (jsi::Runtime& runtime,
119+
const jsi::Value& thisValue,
120+
jsi::Value* args,
121+
size_t count) -> jsi::Value {
122+
callFunction(function, args, std::index_sequence_for<Args...>{});
123+
};
124+
}
100125
};
101126

102127
template <typename ElementType> struct JSIConverter<std::vector<ElementType>> {

0 commit comments

Comments
 (0)