golang生成.a文件被C調(diào)用遇到的坑

golang二維碼掃描:

代碼:https://github.com/tuotoo/qrcode

安裝:go get github.com/tuotoo/qrcode
(首先必須設(shè)置環(huán)境變量GOPATH的路徑)

tuotoo/qrcode代碼調(diào)試:

package main
import (
    "github.com/tuotoo/qrcode"
    "log"
    "os"
)
func main() {
    logger := log.New(os.Stdout, "[bar]", log.Lshortfile|log.Ldate|log.Ltime)
    fi, err := os.Open("qrcode.png")
    if err != nil {
        logger.Println(err.Error())
        return
    }
    defer fi.Close()
    qrmatrix, err := qrcode.Decode(fi)
    if err != nil {
        logger.Println(err.Error())
        return
    }
    logger.Println(qrmatrix.Content)
}

go build tuotoo-qrcode.go 會生成可執(zhí)行文件./tuotoo-qrcode

logger是日志輸出的是標(biāo)準(zhǔn)庫庫包,如
log.New(os.Stdout, "[bar]", log.Lshortfile|log.Ldate|log.Ltime)

生成.a文件(.h文件也會自動生成)

創(chuàng)建文件pkgqrcode.go

package main

import "C"

import (
    //"fmt"
    "github.com/tuotoo/qrcode"
    "os"
)

//export GetQrcodeString
func GetQrcodeString(cstring *C.char) *C.char {
    //func GetQrcodeString() *C.char {
    path := C.GoString(cstring)
    //path := "qrcode.png"
    fi, err := os.Open(path)
    if err != nil {
        //fmt.Println(err.Error())
        return C.CString(path)
    }
    defer fi.Close()
    qrmatrix, err := qrcode.Decode(fi)
    if err != nil {
        //fmt.Println(err.Error())
        return C.CString(path)
    }
    //fmt.Println(qrmatrix.Content)
    //return C.Cstring(qrmatrix.Content)
    gostr := qrmatrix.Content
    cstr := C.CString(gostr)
    return cstr
}

func main() {
}
  • import "C" 的作用就是go代碼中使用C函數(shù)
  • 需要加//export GetQrcodeString 才會生成.h文件(不知道什么?。。?/li>
  • C.GoString(cstring) 把C字符串轉(zhuǎn)成go字符串
  • C.CString(gostr) 把go字符串轉(zhuǎn)成C字符串

編譯步驟
生成.a文件命令(進(jìn)入pkgqrcode.go代碼目錄)執(zhí)行:

go build -buildmode=c-archive -o pkgqrcode.a pkgqrcode.go

生成結(jié)果
pkgqrcode.a
pkgqrcode.h

C代碼調(diào)用.a文件

創(chuàng)建文件c-qrcode.c

#include <stdio.h>
#include "pkgqrcode.h"

void reverse(char *str)
{
    printf("%s\n", str);
    char *ret = GetQrcodeString(str);
    //printf("%s\n",ret); 
}
int main(int argc, char const *argv[])
{
    reverse((char *)argv[1]); 
    return 0;
}

編譯步驟

gcc c-qrcode.c pkgqrcode.a -o c-qrcode

生成可執(zhí)行文件
c-qrcode
執(zhí)行結(jié)果(qrcode.png二維碼內(nèi)容是http://www.baidu.com)

./c-qrcode qrcode.png 
qrcode.png
http://www.baidu.com

遇到問題:
在macOS編譯生成的pkgqrcode.a文件和在linux平臺編譯不能互用(估計是系統(tǒng)內(nèi)核問題)

參考文章:
http://www.cnblogs.com/magicsoar/p/7002467.html
https://studygolang.com/articles/7128

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容