MyNativePlugin.cpp 1.8 KB

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