Skip to content

Instantly share code, notes, and snippets.

@kuc-arc-f
Last active June 22, 2026 09:11
Show Gist options
  • Select an option

  • Save kuc-arc-f/465504d2e2b7a0fb241e9e141b757005 to your computer and use it in GitHub Desktop.

Select an option

Save kuc-arc-f/465504d2e2b7a0fb241e9e141b757005 to your computer and use it in GitHub Desktop.
node.js C++ , call so(Shared Object) function

node.js C++ , call so(Shared Object) function


  • 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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment