jeck猫
编写node的C/C++原生扩展[1]打开Windows命令行cmd.exe,进入D:\node-v0.10.5,执行vcbuild.bat release,最后会在D:\node-v0.10.5\Release目录下可以找到编译好的node.exe、node.lib等文件。[2]制作编译安装批处理文件,此处命名为nodins.bat,文件内容如下:@echo offif "%1"=="" goto helpmkdir "%1"mkdir "%1"\includecopy /y src\node.h "%1"\includecopy /y src\node_object_wrap.h "%1"\includecopy /y src\node_buffer.h "%1"\includecopy /y src\node_version.h "%1"\includecopy /y deps\v8\include\*.h "%1"\include\copy /y deps\uv\include\*.h "%1"\include\mkdir "%1"\include\uv-privatecopy /y deps\uv\include\uv-private\*.h "%1"\include\uv-privatemkdir "%1"\include\evcopy /y deps\uv\src\ev\*.h "%1"\include\evmkdir "%1"\include\c-arescopy /y deps\uv\include\ares.h "%1"\include\c-arescopy /y deps\uv\include\ares_version.h "%1"\include\c-aresmkdir "%1"\libcopy /y Release\node.lib "%1"\libcopy /y Release\node.exe "%1"echo =================================echo Install succeefully!goto exitif not errorlevel 0 echo Error "install-path" & goto exit:helpecho nodins.bat install-path:exit[3]打开Windows命令行cmd.exe,切换 进入D:\node-v0.10.5目录。将文件nodins.bat拷贝到D:\node-v0.10.5中,在命令行执行:nodins.bat D:\nodejs,则生成编译C/C++扩展的编译环境(包括头文件、库和可执行文件)D:\nodejs目录,内容如下:[4]用Visual Studio 2010创建一个DLL工程空白工程hellonode放在D:\目录下,新建项目—>win32控制台程序,然后进入如下页面:[5]创建一个C++文件如hellonode.cpp,代码如下:#define BUILDING_NODE_EXTENSION#include <node.h>using namespace v8;Handle<Value> Hello(const Arguments& args) {HandleScope scope;return scope.Close(String::New("Hello world!"));}Handle<Value> Add(const Arguments& args) {HandleScope scope;if (args.Length() < 2) {ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));return scope.Close(Undefined());}if (!args[0]->IsNumber() || !args[1]->IsNumber()) {ThrowException(Exception::TypeError(String::New("Wrong arguments")));return scope.Close(Undefined());}Local<Number> num = Number::New(args[0]->NumberValue() +args[1]->NumberValue());return scope.Close(num);}void init(Handle<Object> target) {NODE_SET_METHOD(target, "hello", Hello);NODE_SET_METHOD(target, "add", Add);}NODE_MODULE(hellonode, init)[6]在工程属性的配置属性-常规中将输出目录改为.\;[7]在工程属性的配置属性-常规中将目标文件扩展名改为.node;[8]在工程属性的配置属性-C/C++-常规-附加包含目录添加头文件目录为:D:\nodejs\include[9]在工程属性的配置属性-链接器-常规-附加库目录添加目录:D:\nodejs\lib[10]在工程属性的配置属性-链接器-输入-附加依赖项添加lib库:node.lib[11]编译生成后在D:\hellonode\hellonode中生成一个文件hellonode.node;[12]在D:\hellonode目录创建js测试代码test.js,代码如下:var addons = require('./hellonode');console.log('C/C++ addons.hello() =', addons.hello());console.log('C/C++ addons.add(200, 300) =', addons.add(200, 300));[13]在命令行执行node .\test.js(若未配置node.exe的路径变量,则执行:D:\nodejs\node .\test.js)