环境
Nodejs 版本:v16.20.0
操作系统:Ubuntu 18.04.6 LTS
安装ffi
npm install ffi-napi ref-napi ref-struct-napi
编写库代码
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
void print_message(const char* message) {
printf("Message from C: %s\n", message);
}
void test(const char* message) {
printf("Message from C: %s\n", message);
}
编译C库
gcc -shared -o libmylib.so -fPIC mylib.c
使用ffi调用C库
const ffi = require('ffi-napi');
const ref = require('ref-napi');
// 定义返回值类型和参数类型
const intType = ref.types.int;
const stringType = ref.types.CString;
// 加载库(选择库文件)
const libFileName = './libmylib.so';
const mylib = ffi.Library(libFileName, {
'add': [intType, [intType, intType]],
'print_message': ['void', [stringType]]
});
// 调用 C 函数
const result = mylib.add(5, 10);
console.log(`Result: ${result}`); // Output: Result: 15
// 调用打印函数
mylib.print_message('Hello from Node.js!');