MyNativePlugin.cpp 1.6 KB

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