c++로 만들어진 코드를 바인딩하기 정보
node.js c++로 만들어진 코드를 바인딩하기본문
1. N-API를 사용하여 C++ 애드온 정의
- N-API 는 c++ 애드온하기 위한 빌드, v8엔진과 독립적이며 안정적인 ABI ( Application Binary Interface )
- js만으로 사용하기에는 OS API를 접근하기 힘들기 때문에 대안이 될 수 있음
- 유용한 c++ 라이브러리를 래핑하여 개발할 수 있음
- 성능 좋은 c++모듈을 바인딩할 수 있음
2. 필요패키지 및 실행환경
- node-gyp
- bindings
- node-addon-api
- 실행환경 : g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
3. 패키지 설치
프로젝트 디렉토리를 생성하고 npm 초기화
$ npm init
node-gyp를 전역설치를 합니다.
$ npm install -g node-gyp
bindings를 설치합니다.
$ npm install bindings
node-addon-api 설치합니다.
$ npm install node-addon-api
4. 바인딩 설정
vi로 binding.gyp를 파일을 만들어서 아래처럼 설정합니다.
{
"targets": [
{
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"include_dirs" : [
"<!@(node -p \"require('node-addon-api').include\")"
],
"target_name": "./gnu_hello",
"sources": [ "gnu_hello.cpp" ],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]
}
]
}
5. cpp 라이브러리 만들기
//gnu_hello.cpp
#include <napi.h>
Napi::String GnuMsg(const Napi::CallbackInfo& info) {
//javascript를 생성하위한 객체
Napi::Env env = info.Env();
return Napi::String::New(env, "Hellow gnu world");
}
Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "GnuMsg"), Napi::Function::New(env, GnuMsg));
return exports;
}
NODE_API_MODULE(gnu_hello, InitAll);
6. c++ 빌드하기
$ node-gyp rebuild
빌드에 성공을 하면 gyp info ok가 나옵니다. 저는 빌드를 우분투 20.0.4 에서 하였습니다. build 디렉토리에 Release 디렉토리가 생길텐데 그것도 한번 확인해 보셔야 합니다.
gnu_hello파일이 생성되었습니다. 이 경로로 직접 바인딩하여 사용할 수 있습니다.
7. nodejs 사용하기
//index.js 파일 생성하여 아래 코드처럼 만들어주세요
const addon = require("bindings")("gnu_hello");
const str = addon.GnuMsg();
console.log(str);
8. nodejs 프로젝트 실행
아래 코드를 실행해 봅시다. 아래 이미지 처럼 Hellow gnu world가 나옵니다.
$ node index.js
참고 링크 : https://morioh.com/p/e1a6f79af449
참고 링크 : https://nodejs.org/api/addons.html#addons_worker_support
!-->!-->!-->!-->!-->!-->!-->!-->!-->1