- node setup
npm init -y
npm i koffi
- C++ build
g++ -shared -fPIC sample.cpp -o libsample.so
- start
node main
| const koffi = require('koffi'); | |
| // so をロード | |
| const lib = koffi.load('./libsample.so'); | |
| // 関数シグネチャを定義 (extern "C" 前提) | |
| const myFunc = lib.func('int add(int a, int b)'); | |
| const myGreet = lib.func('const char* greet(const char* name)'); | |
| // 呼び出し | |
| const result = myFunc(10, 25); | |
| console.log("myFunc:", result); | |
| const resp_greet = myGreet("hello-123"); | |
| console.log("myGreet:" ,resp_greet); |
| { | |
| "name": "so_test1", | |
| "version": "1.0.0", | |
| "description": "", | |
| "main": "index.js", | |
| "scripts": { | |
| "test": "echo \"Error: no test specified\" && exit 1" | |
| }, | |
| "keywords": [], | |
| "author": "", | |
| "license": "ISC", | |
| "dependencies": { | |
| "koffi": "^3.0.2" | |
| } | |
| } |
| #include <iostream> | |
| #include <string> // 文字列を扱うために必要 | |
| #include <cstring> | |
| extern "C" { | |
| int add(int a, int b) | |
| { | |
| return a + b; | |
| } | |
| const char* hello() | |
| { | |
| return "Hello From C++"; | |
| } | |
| const char* greet(const char* name) | |
| { | |
| static std::string msg; | |
| msg = "Hello "; | |
| msg += name; | |
| return msg.c_str(); | |
| } | |
| } |