MyNativePlugin.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Javascript Usage:
  3. // require our native plugin like any other JS module
  4. require("MyNativePlugin");
  5. // call our native method
  6. var answer = NativePlugin.getAnswer();
  7. print("The answer is: ", answer, " which is " , NativePlugin.checkAnswer(answer) ? "correct" : "incorrect");
  8. */
  9. // ATOMIC_PLUGIN_MAIN must be defined in one (and only one) plugin source file
  10. // before including AtomicPlugin.h
  11. #define ATOMIC_PLUGIN_MAIN
  12. #include "AtomicPlugin.h"
  13. // define C linkage so that we can easily get functions from shared library
  14. extern "C"
  15. {
  16. // a cfunction which returns the answer to life, the universe, and everything
  17. static int js_getAnswer(duk_context* ctx)
  18. {
  19. duk_push_number(ctx, 42);
  20. return 1;
  21. }
  22. // a cfunction which checks that the answer is correct
  23. static int js_checkAnswer(duk_context* ctx)
  24. {
  25. int answer = duk_require_int(ctx, 0);
  26. answer == 42 ? duk_push_true(ctx) : duk_push_false(ctx);
  27. return 1;
  28. }
  29. // the function list that out native plugin exports
  30. static const duk_function_list_entry plugin_funcs[] = {
  31. { "getAnswer", js_getAnswer, 0 /*nargs*/ },
  32. { "checkAnswer", js_checkAnswer, 1 /*nargs*/ },
  33. { NULL, NULL, 0 }
  34. };
  35. // main plugin initialization function, which is a standard Duktape cfunction
  36. // must use PLUGIN_EXPORT_API for function to be exported from dll on Windows
  37. int PLUGIN_EXPORT_API atomic_plugin_init(duk_context* ctx)
  38. {
  39. // modules's exports object should be at index 0
  40. if (!duk_get_top(ctx) || !duk_is_object(ctx, 0))
  41. {
  42. // not an object, something went wrong
  43. duk_push_boolean(ctx, 0);
  44. return 1;
  45. }
  46. // export our native functions
  47. duk_put_function_list(ctx, 0, plugin_funcs);
  48. // and return success
  49. duk_push_boolean(ctx, 1);
  50. return 1;
  51. }
  52. }