- npm install
npm i koffi
- C++ build
clang++ -shared sample.cpp -o sample.dll
- start
node main
| const koffi = require('koffi'); | |
| // DLLのロード(.dll拡張子は省略可) | |
| const lib = koffi.load('./sample.dll'); | |
| // 関数の定義: 戻り値型, 関数名, [引数型...] | |
| const add = lib.func('int add(int a, int b)'); | |
| const multiply = lib.func('double multiply(double a, double b)'); | |
| const getMessage = lib.func('const char* get_message()'); | |
| const greet = lib.func('const char* greet(const char* name)'); | |
| // 実行 | |
| console.log(add(3, 5)); // 8 | |
| console.log(multiply(2.5, 4)); // 10.0 | |
| console.log(getMessage()); // 10.0 | |
| const g1 = greet("テスト文字-TEST-001"); | |
| console.log("g1=", g1); | |
| #include <windows.h> | |
| #include <string> | |
| // extern "C" でC言語リンクとし、__declspec(dllexport) でエクスポート | |
| extern "C" { | |
| __declspec(dllexport) int add(int a, int b) { | |
| return a + b; | |
| } | |
| __declspec(dllexport) double multiply(double a, double b) { | |
| return a * b; | |
| } | |
| __declspec(dllexport) const char* get_message() | |
| { | |
| return "Hello World"; | |
| } | |
| __declspec(dllexport) const char* greet(const char* name) | |
| { | |
| static std::string msg; | |
| msg = "Hello "; | |
| msg += name; | |
| return msg.c_str(); | |
| } | |
| } |