Language/Node.js
node-gyp을 이용한 C/C++ native library를 nodejs 모듈로 만들기
미니옵빠
2017. 6. 30. 22:01
Node.js addon
- Node.js Addons are dynamically-linked shared objects, written in C++, that can be loaded into Node.js using the require() function, and used just as if they were an ordinary Node.js module
- C / C++ 라이브러리를 Node.js에서 module 형태로 사용가능합니다.
addon 작성 기초
node-gyp를 이용한 기본 사용법은 아래를 참고하면 됩니다.
c++ 샘플 파일 작성부터 build, node.js 모듈로 사용법까지 잘 설명되어 있습니다.
- Node.js v8.1.2 Documentation: https://nodejs.org/api/addons.html
- Node.js C++ addon examples: https://github.com/nodejs/node-addon-examples
binding.gyp
작성
GYP Doc
- GYP User Documentation: https://gyp.gsrc.io/docs/UserDocumentation.md
- GYP Language Specification: https://gyp.gsrc.io/docs/LanguageSpecification.md
시작
- 기존 모듈의 Makefile이 있어야 합니다. 아니면 컴파일 옵션과 link 정보를 제작자로부터 알아냅니다.
- 컴파일 옵션은
CFLAGS(CXXFLAGS )
변수로 사용합니다. Makefile을 열어 여기 사용되는 내용을 작성해 둡니다. (변수값 반영된 걸로 풀어서) - link 정보는
LDFLAGS
변수로 사용합니다. Makefile을 얼어 사용되는 link 정보를 잘 기록해 둡니다. (조금 있다 찾으러 가야 합니다)
binding.gyp
파일 내 옵션 작성
- 컴파일 전처리 과정에 필요한 헤더 파일 include 경로는
targets.include_dirs
에 기록합니다. CFLAGS
내용은targets.cflags
에 기록합니다. 이 때-l
옵션으로 사용된 include path는 바로 위에서 기록되었으므로, 여기서는 제거합니다.LDFLAGS
내용은targets.libraries
에 기록합니다. 이 때-L
의 디렉토리명과-l
의 라이브러리 파일을 합쳐 fullpath로 기록합니다.-L/lib -lxxxx
->/lib/libxxxx.so
이렇게요.
아래는 이 과정을 거쳐 나온 결과물 예시입니다.
Makefile
$(XXXX_DIR)
는/home/user/apps/xxxx
여기입니다.
CC = g++ -Wall -fPIC
XXXPATH = -DXXX_PATH=\"$(XXXX_DIR)/share\"
INCLUDE = -I$(XXX_DIR)/include
DEBUG = #-g
OPTIMIZE = -O3
CFLAGS = $(TRACE) $(DEBUG) $(OPTIMIZE) $(INCLUDE) $(XXXPATH)
LDFLAGS = -L$(XXX_DIR)/lib -lxxx -lyyyy
RM = rm -f
all : interface
interface :
$(CC) $(CFLAGS) -o interface interface.cpp $(LDFLAGS)
clean :
$(RM) interface *.o
binding.gyp
{
"targets": [
{
"target_name": "xxxx",
"sources": [ "xxxx.cpp" ],
"include_dirs": ["/home/user/apps/xxxx/include"],
"cflags": ["-O3", "-DXXX_PATH=\"/home/user/apps/xxxx/share\""],
"libraries": [
"/home/user/apps/xxxx/lib/libxxxx.so", "/home/user/apps/xxxx/lib/libyyyy.so"
]
}
]
}
cpp
파일 작성 및 Build
- addon 작성 기초에 따라 필요한 cpp 파일을 작성합니다. 대부분 모듈 배포자가 c++로 동작 파일을 만들어 두어, 이 파일에 v8 namespace를 이용한 기본 코드 골격을 추가 작성하면 됩니다.
node-gyp configure
를 실행하여 Makefile 등을 생성합니다.node-gyp build
를 실행하여 최종 addon 파일을 생성합니다.
사용
addon 내에서 native library를 사용하기 때문에, native library가 사용하는 shared library 경로를 지정해 줘야 합니다.
$ export LD_LIBRARY_PATH=/home/user/apps/xxxx/lib
그리고 아래 샘플처럼 addon 최종 결과 파일을 require
로 불러 사용하면 됩니다.
// Loading Addon
const xxxx = require('./build/Release/xxxx');
console.log(xxxx.getXXXX("Test Data"));