Support bridging for Class methods return types (#51223)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51223

Changelog:
[General][Added] - Added support for bridging Class methods return types

Previously, this wouldn't work, unless you define your C++ implementation of the TM to have primitive return type that can be converted to JavaScript's type.

Reviewed By: javache

Differential Revision: D74478572

fbshipit-source-id: 75c7f589559394704446be1ebac245d38a5c4b2b
This commit is contained in:
Ruslan Lesiutin
2025-05-12 12:38:58 -07:00
committed by Facebook GitHub Bot
parent 775c16d8b4
commit e403b510d0
2 changed files with 59 additions and 2 deletions
@@ -41,7 +41,7 @@ T callFromJs(
rt, fromJs<Args>(rt, std::forward<JSArgs>(args), jsInvoker)...);
return jsi::Value();
} else if constexpr (is_jsi_v<T>) {
} else if constexpr (is_jsi_v<T> || supportsToJs<R, T>) {
static_assert(supportsToJs<R, T>, "Incompatible return type");
return toJs(
@@ -49,7 +49,6 @@ T callFromJs(
(instance->*method)(
rt, fromJs<Args>(rt, std::forward<JSArgs>(args), jsInvoker)...),
jsInvoker);
} else if constexpr (is_optional_jsi_v<T>) {
static_assert(
is_optional_v<R>
@@ -92,4 +92,62 @@ TEST_F(BridgingTest, callFromJsTest) {
EXPECT_TRUE(called);
}
struct MethodReturnTypeCastingTestObject {
public:
explicit MethodReturnTypeCastingTestObject(int value) : value_(value) {}
int toInteger() const {
return value_;
}
private:
int value_;
};
template <>
struct Bridging<MethodReturnTypeCastingTestObject> {
static MethodReturnTypeCastingTestObject fromJs(
jsi::Runtime& /*rt*/,
const jsi::Value& value) {
return MethodReturnTypeCastingTestObject(
static_cast<int>(value.asNumber()));
}
static int toJs(
jsi::Runtime& /*rt*/,
const MethodReturnTypeCastingTestObject& value) {
return value.toInteger();
}
};
struct MethodReturnTypeCastingTestClass {
explicit MethodReturnTypeCastingTestClass(
std::shared_ptr<CallInvoker> invoker)
: invoker_(std::move(invoker)) {}
// This is the key, return type is not a primitive, but an object with defined
// bridging template.
MethodReturnTypeCastingTestObject
add(jsi::Runtime& /*unused*/, int a, int b) {
return MethodReturnTypeCastingTestObject(a + b);
}
private:
std::shared_ptr<CallInvoker> invoker_;
};
TEST_F(BridgingTest, methodReturnTypeCastingTest) {
auto instance = MethodReturnTypeCastingTestClass(invoker);
EXPECT_EQ(
2,
bridging::callFromJs<int>(
rt,
&MethodReturnTypeCastingTestClass::add,
invoker,
&instance,
1,
1));
}
} // namespace facebook::react