c++写nodejs的扩展模块(一)

2015-01-27 06:07:49 · 作者: · 浏览: 37

c++写nodejs的扩展模块

by 伍雪颖
\
记住目录各文件的位置,主要是3个文件,hello.cc,binding.gyp,hello.js
hello.cc代码:
#include 
  
   
#include 
   
     using namespace v8; Handle
    
      SayHello(const Arguments& args) { HandleScope scope; return scope.Close(String::New("Hello world!")); } void Init_Hello(Handle
      target) { target->Set(String::NewSymbol("SayHello"),FunctionTemplate::New(SayHello)->GetFunction()); } NODE_MODULE(hello,Init_Hello) 
binding.gyp代码:
{
	'targets':[
	{
	'target_name':'hello',
	'sources':['src/hello.cc'],
	}]
}

写好这两个文件后,编译生成模块文件: 1.要用到node-gyp工具 安装:npm install -g node-gyp 2.安装后编译: node-gyp configure node-gyp build 3.编译成功后,会在build/Release目录下出现一个hello.node文件
一般都会编译成功的,我原来binding.gyp文件内容是: {
'targets':[
{
'target_name':'hello',
'sources':['src/hello.cc'],
'conditions':[['OS == "mac"',
{
'libraries':['-lnode.lib']
}]]
}]
} 这样会报缺少-lnode.lib的错误,多此一举了,不要加就行!
接下来是调用它: hello.js代码:
var hello = require('./build/Release/hello.node');
console.log(hello.SayHello());

执行: node hello.js 成功输出hello world!
<script type="text/java script">
<script type="text/java script">BAIDU_CLB_fillSlot("771048");
点击复制链接 与好友分享! 回本站首页
<script> function copyToClipBoard(){ var clipBoardContent=document.title + '\r\n' + document.location; clipBoardContent+='\r\n'; window.clipboardData.setData("Text",clipBoardContent); alert("恭喜您!复制成功"); }
<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
您对本文章有什么意见或着疑问吗?请到 论坛讨论您的关注和建议是我们前行的参考和动力??
上一篇: leetcode[99] Recover Binary Search Tree
下一篇: 01背包 HDU3466
相关文章
实用C++函数:取当前模块句柄
C++中模块(Dll)对外暴露接口的几种方式
<script type="text/java script">BAIDU_CLB_fillSlot("182716");
<script type="text/java script">BAIDU_CLB_fillSlot("517916");
图文推荐
<iframe src="http://www.2cto.com/uapi.php?tid=355850&catid=339&title=Yysr0LRub2RlanO1xMCp1bnEo7/p&forward=http://www.2cto.com/kf/201411/355850.html" width="100%" height="100%" id="comment_iframe" name="comment_iframe" frameborder="0" scrolling="no">
<script type="text/java script">BAIDU_CLB_fillSlot("771057");
排行
热门
<script typ