三木社区

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 245|回复: 0
打印 上一主题 下一主题

C++插件-工厂模式

[复制链接]

1562

主题

1564

帖子

4904

积分

博士

Rank: 8Rank: 8

积分
4904
跳转到指定楼层
楼主
发表于 2017-8-8 08:02:10 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
这个模式里展示了如何创建并返回一个 JavaScript 函数,它是由 C++ 函数包装的 :
  1. // addon.cc
  2. #include <node.h>

  3. using namespace v8;

  4. void MyFunction(const FunctionCallbackInfo<Value>& args) {
  5.   Isolate* isolate = Isolate::GetCurrent();
  6.   HandleScope scope(isolate);
  7.   args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
  8. }

  9. void CreateFunction(const FunctionCallbackInfo<Value>& args) {
  10.   Isolate* isolate = Isolate::GetCurrent();
  11.   HandleScope scope(isolate);

  12.   Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  13.   Local<Function> fn = tpl->GetFunction();

  14.   // omit this to make it anonymous
  15.   fn->SetName(String::NewFromUtf8(isolate, "theFunction"));

  16.   args.GetReturnValue().Set(fn);
  17. }

  18. void Init(Handle<Object> exports, Handle<Object> module) {
  19.   NODE_SET_METHOD(module, "exports", CreateFunction);
  20. }

  21. NODE_MODULE(addon, Init)
复制代码
测试:
  1. // test.js
  2. var addon = require('./build/Release/addon');

  3. var fn = addon();
  4. console.log(fn()); // 'hello world'
复制代码


回复

使用道具 举报

Archiver|手机版|小黑屋|三木电子社区 ( 辽ICP备11000133号-4 )

辽公网安备 21021702000620号

GMT+8, 2025-6-27 00:13 , Processed in 0.027406 second(s), 23 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表