-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathRnExecutorchInstaller.h
More file actions
77 lines (65 loc) · 2.67 KB
/
RnExecutorchInstaller.h
File metadata and controls
77 lines (65 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#pragma once
#include <memory>
#include <string>
#include <thread>
#include <ReactCommon/CallInvoker.h>
#include <jsi/jsi.h>
#include <rnexecutorch/host_objects/JsiConversions.h>
#include <rnexecutorch/host_objects/ModelHostObject.h>
namespace rnexecutorch {
using FetchUrlFunc_t = std::function<std::vector<std::byte>(std::string)>;
extern FetchUrlFunc_t fetchUrlFunc;
using namespace facebook;
class RnExecutorchInstaller {
public:
static void
injectJSIBindings(jsi::Runtime *jsiRuntime,
std::shared_ptr<react::CallInvoker> jsCallInvoker,
FetchUrlFunc_t fetchDataFromUrl);
private:
template <typename ModelT>
static jsi::Function
loadModel(jsi::Runtime *jsiRuntime,
std::shared_ptr<react::CallInvoker> jsCallInvoker,
const std::string &loadFunctionName) {
return jsi::Function::createFromHostFunction(
*jsiRuntime, jsi::PropNameID::forAscii(*jsiRuntime, loadFunctionName),
0,
[jsCallInvoker](jsi::Runtime &runtime, const jsi::Value &thisValue,
const jsi::Value *args, size_t count) -> jsi::Value {
if (count != 1) {
char errorMessage[100];
std::snprintf(
errorMessage, sizeof(errorMessage),
"Argument count mismatch, was expecting: 1 but got: %zu",
count);
throw jsi::JSError(runtime, errorMessage);
}
try {
auto source =
jsiconversion::getValue<std::string>(args[0], runtime);
auto modelImplementationPtr =
std::make_shared<ModelT>(source, jsCallInvoker);
auto modelHostObject = std::make_shared<ModelHostObject<ModelT>>(
modelImplementationPtr, jsCallInvoker);
return jsi::Object::createFromHostObject(runtime, modelHostObject);
} catch (const std::runtime_error &e) {
// This catch should be merged with the next one
// (std::runtime_error inherits from std::exception) HOWEVER react
// native has broken RTTI which breaks proper exception type
// checking. Remove when the following change is present in our
// version:
// https://github.com/facebook/react-native/commit/3132cc88dd46f95898a756456bebeeb6c248f20e
throw jsi::JSError(runtime, e.what());
return jsi::Value();
} catch (const std::exception &e) {
throw jsi::JSError(runtime, e.what());
return jsi::Value();
} catch (...) {
throw jsi::JSError(runtime, "Unknown error");
return jsi::Value();
}
});
}
};
} // namespace rnexecutorch