golang二維碼掃描:
安裝: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 會(huì)生成可執(zhí)行文件./tuotoo-qrcode
logger是日志輸出的是標(biāo)準(zhǔn)庫庫包蓝撇,如
log.New(os.Stdout, "[bar]", log.Lshortfile|log.Ldate|log.Ltime)
生成.a文件(.h文件也會(huì)自動(dòng)生成)
創(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 才會(huì)生成.h文件(不知道什么!3旅А)
- 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ái)編譯不能互用(估計(jì)是系統(tǒng)內(nèi)核問題)
參考文章:
http://www.cnblogs.com/magicsoar/p/7002467.html
https://studygolang.com/articles/7128