Ⅰ. はじめに
タイトルの通り「Node.jsからDLL(C++)を呼び出す方法」です。
Ⅱ. やり方
1. DLLを作成する
Source.cpp
#include <Windows.h> #include <iostream> void Hello1() { std::cout << "hello world" << std::endl; } void Hello2(char str[]) { std::cout << "hello " << str << std::endl; } void Hello3(wchar_t str[]) { std::wcout << "hello " << str << std::endl; } int Sum(int a, int b) { return a + b; } BOOL WINAPI DllMain(HINSTANCE hinstModule, DWORD dwReason, LPVOID lpvReserved) { if (dwReason == DLL_PROCESS_ATTACH) { DisableThreadLibraryCalls(hinstModule); } return TRUE; }
2. ffi をインストールする
// Windowsのみ // npm install --global --production windows-build-tools npm install ffi
3.サンプルプログラムを書く
index.js
const ffi = require('ffi'); const lib = ffi.Library('c:\\test.dll', { 'Hello1': ['void', []], 'Hello2': ['void', ['string']], 'Hello3': ['void', [ref.types.CString]], 'Sum': ['int', ['int', 'int']] }); lib.Hello1(); lib.Hello2('tanaka'); lib.Hello3(Buffer.from('tanaka\0', 'utf16le')); let result = lib.Sum(1, 2); console.log(result);
実行結果
$ node index.js hello world hello tanaka hello tanaka 3