我试图使用node访问cpp库并使用这些函数。math.cc是cc文件,包含所有函数的定义。使用构建代码。生成.so文件,由math.js访问。
math.cc
#include "math.h"
int add(int x, int y)
{
return x + y;
}
int minus(int x, int y)
{
return x - y;
}
int multiply(int x, int y)
{
return x * y;
}头文件
int add(int a, int b);
int minus(int a, int b);
int multiply(int a, int b);导出函数的math.js
var ffi = require('ffi');
var ref = require('ref');
var int = ref.types.int;
var platform = process.platform;
var mathlibLoc = null;
if (platform === 'win32'){
mathlibLoc = './math.dll';
}else if(platform === 'linux'){
mathlibLoc = './build/Release/obj.target/math.so';
}else if(platform === 'darwin'){
mathlibLoc = './math.dylib'
}else{
throw new Error('unsupported plateform for mathlibLoc')
}
var math = ffi.Library(mathlibLoc, {
"add": [int, [int, int]],
"minus": [int, [int, int]],
"multiply": [int, [int, int]]
});
module.exports = math;存取功能
test.js
var math = require('./math');
var result = null;
result = math.add(5, 2);
console.log('5+2='+result);
result = math.minus(5, 2);
console.log('5-2='+result);
result = math.multiply(5, 2);
console.log('5*2='+result);给出错误。请帮帮忙。
发布于 2019-08-19 09:04:14
由于cpp中的代码,如果我们想要访问node中的cpp库,就需要执行extern "C“。
#include <stdint.h>
#if defined(WIN32) || defined(_WIN32)
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
extern "C" EXPORT int add(int a, int b) {
return a + b;
}这将解决错误。
https://stackoverflow.com/questions/57552035
复制相似问题