Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example of native interop (NativeFunction, etc)? #40

Closed
alastaircoote opened this issue Jul 16, 2019 · 2 comments
Closed

Example of native interop (NativeFunction, etc)? #40

alastaircoote opened this issue Jul 16, 2019 · 2 comments

Comments

@alastaircoote
Copy link

I'm curious to play around with Hermes outside of the React Native context, with my own C++ code. From looking through the code it looks as though things like NativeFunction are what I want to be using, but I'm curious to know if there is a good example anywhere of declaring a native function or class, adding it to a context and running it?

@dulinriley
Copy link
Contributor

There are some examples in the React Native codebase, and the important file to look at is jsi.h.
There’s a function called jsi::Function::createFromHostFunction.

It’s used like this:

  /// Create a function which, when invoked, calls C++ code. If the
  /// function throws an exception, a JS Error will be created and
  /// thrown.
  /// \param name the name property for the function.
  /// \param paramCount the length property for the function, which
  /// may not be the number of arguments the function is passed.
  static Function createFromHostFunction(
      Runtime& runtime,
      const jsi::PropNameID& name,
      unsigned int paramCount,
      jsi::HostFunctionType func);

…

void foo(Runtime &rt) {
  const auto fooImpl = [](Runtime &rt, const Value& thisVal, const Value* args, size_t count) -> Value {
    // Do whatever you want in here.
    return args[0];
  };
  auto fooPropName = PropNameID::forAscii(rt, “foo”);
  auto func = Function::createFromHostFunction(rt, fooPropName, 1, fooImpl);
  rt.global().setProperty(rt, fooPropName, std::move(func));
  // You can also call existing host functions.
  rt.global().getPropertyAsFunction(rt, “foo”).call(rt, {Value(2)});
}

That should be the basics of setting up your own NativeFunctions.

@alastaircoote
Copy link
Author

Awesome. Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants