golang调用c库函数
- 本文章介绍了golang如何调用c语言库函数。如果想调用c++库函数,建议在c++上再封一层c语言代码,编译成c语言动态库,再被golang调用。
c语言相关代码
#ifndef __MYTEST_H_
#define __MYTEST_H_
#ifdef __cplusplus
extern "C" {
#endif
int TestCgo(const char *buffer, unsigned int length);
#ifdef __cplusplus
}
#endif
#endif /* __MYTEST_H_*/
golang相关代码
package cgotest
// #cgo LDFLAGS: -L./lib -lwrappertest -Wl,-rpath,/usr/local/lib -Wl,-rpath,$ORIGIN/lib
// #cgo CFLAGS: -I./include
// #include "mytest.h"
import "C"
import (
"fmt"
"unsafe"
)
type fakeString struct {
Data *C.char
Len int
}
func test() {
var s string = "helloworld"
cString := (*fakeString)(unsafe.Pointer(&s))
cData := cString.Data
cLen := C.uint(len(s))
fmt.Println(C.TestCgo(cData, cLen)
}
golang编译
go build -o test