我是靠谱客的博主 超级指甲油,最近开发中收集的这篇文章主要介绍node-ffi 调用Golang动态库,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

node-ffi 调用Golang动态库

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

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 部分

//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 调用Golang动态库所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部