1.cgo简单调用
package main
/*
#include <stdio.h>
void print1(char* s){
printf("print from c code: %s\n", s);
}
*/
import "C"
func main() {
text := C.CString("ABC")
C.print1(text)
}
官方文档:The Go file will have access to anything appearing in the comment immediately preceding(在…之前) the line import "C"
2.c结构体调用
package main
/*
typedef struct {
char* name;
int age;
} Student;
*/
import "C"
import "fmt"
func main() {
var stu C.Student;
stu.name = C.CString("test")
stu.age = 20
fmt.Println(C.GoString(stu.name))
fmt.Println(stu.age)
}
C语言和Go语言字符串转换函数
func C.CString(goString string) *C.char
func C.GoString(cString *C.char) string
func C.GoStringN(cString *C.char, length C.int) string
3.c字符数组赋值
package main
/*
typedef struct {
char name[255];
int age;
} Student;
*/
import "C"
import "fmt"
const bufferSize = 255
/**
Golang字符串转换为C的字符数组
*/
func GoString2CCharArray(text string) [bufferSize]C.char {
result := [bufferSize]C.char{}
for i := 0; i < len(text) && i < bufferSize; i++ {
result[i] = C.char(text[i])
}
return result
}
/**
C字符数组转换为Golang字符串
*/
func CCharArray2GoString(array [bufferSize]C.char) string {
//func C.GoString(cString *C.char) string
var result = C.GoString(&array[0])
return result
}
func main() {
var stu C.Student
stu.name = GoString2CCharArray("name from go")
stu.age = 20
fmt.Println(CCharArray2GoString(stu.name))
fmt.Println(stu.age)
}
4.访问c结构体数组
package main
/*
typedef struct {
char* name;
int age;
} Student;
Student student_list[2] = {{"A",20},{"B",21}};
*/
import "C"
import "fmt"
func main() {
var stu C.Student
for k, v := range C.student_list {
stu = v
fmt.Println("index: ", k)
fmt.Println(C.GoString(stu.name))
fmt.Println(stu.age)
}
}
网友评论