我是靠谱客的博主 超级指甲油,这篇文章主要介绍node-ffi 调用Golang动态库,现在分享给大家,希望可以做个参考。

node-ffi 调用Golang动态库

node-ffi库以及无维护,尝试使用napi-ffi

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const ffi = require('ffi-napi'); const fs = require('fs'); console.log(process.arch, process.platform); //# 坑 不能使用除开dll其他的后缀 export class AA { static dll; //這個加載太耗時了,这种不是IO,是CPU,所以只等API支持异步 static async load(df) { return new Promise((resolve, reject) => { if (!fs.existsSync(df)) { reject('dll no exist'); return; } const t = Date.now(); console.log('Load Start', t); this.dll = ffi.Library(df, { 'initAABot': ['void', ['string', 'bool']],//类型是go String // 'initDefault': ['void', []], 'runAABot': ['void', ['bool']], 'exitAABot': ['void', []], }); console.log('Load Finish:', Date.now() - t, 'ms'); resolve(); }); } static iniAABot(port) { if (!this.dll) return null; return this.dll.initAaBot(port, true); } //启动 static runAABot() { if (!this.dll) return null; const _self = this; return _self.dll.runAABot(true); } //关闭,关闭后指挥关闭AA资源,不可再次进行开启 static exitAABot() { if (!this.dll) return null; const _self = this; return _self.dll.exitAABot(); } static getAAName() { //if (process.arch) if (process.platform === 'win32') { return 'AA.dll'; } if (process.platform === 'darwin') { return 'AA.so'; } return ''; } }

golang export 部分

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//export initDefault func initDefault() { initBot(":20011", true) } //export initAABot func initAABot(p *C.char, color bool) { port := C.GoString((*C.char)(p)) initBot(port, color) } //export runAABot func runAABot(async bool) { if bot != nil { return } if async { go startBot() //异步启动 } else { startBot() } } //export exitAABot func exitAABot() { if bot != nil { bot.Close() } } func initBot(port string, color bool) { config.Runner = true config.Color = color config.ServerPort = port }

注意

需要注意的是数据类型,如果node调用的时候数据类型传入有误,可能会导致dll雪崩,调用不报错但是运行会崩溃。比如说node string,那么在golang export 中就可以用 *char 来表示

最后

以上就是超级指甲油最近收集整理的关于node-ffi 调用Golang动态库的全部内容,更多相关node-ffi内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(104)

评论列表共有 0 条评论

立即
投稿
返回
顶部