测试环境:Linux
第一部分:C代码
(1)头文件 person.h
#ifndef PERSON_H
#define PERSON_H
typedef struct APerson {
const char * name;
const char * long_name;
} APerson ;
APerson *get_person(const char * name, const char * long_name);
#endif /* !PERSON_H */
(2)源文件 person.c
#include <stdlib.h>
#include "person.h"
APerson *get_person(const char *name, const char *long_name){
APerson *fmt = malloc(sizeof(APerson));
fmt->name = name;
fmt->long_name = long_name;
return fmt;
};
(3)编译成共享库文件
gcc -o libperson.so -Wall -g -shared -fPIC person.c
第二部分:go 代码
(1) main.go
package main
/*
#cgo CFLAGS: -g -Wall
#cgo LDFLAGS: -L. -lperson
#include "person.h"
*/
import "C"
import (
"fmt"
)
type (
Person C.struct_APerson
)
func (p *Person) Name() string {
return C.GoString(p.name)
}
func (p *Person) LongName() string {
return C.GoString(p.long_name)
}
func GetPerson(name string, long_name string) *Person {
return (*Person)(C.get_person(C.CString(name), C.CString(long_name)))
}
func main(){
var f *Person
f = GetPerson("tim", "tim hughes")
fmt.Printf("Hello Go world: My name is %s, %s.\n", C.GoString(f.name), C.GoString(f.long_name))
fmt.Printf("Hello Go world: My name is %s, %s.\n", f.Name(), f.LongName())
}
(2) 编译生成可执行文件
go build main.go
(3) 运行及结果:
$export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH
$./main
Hello Go world: My name is tim, tim hughes.
Hello Go world: My name is tim, tim hughes.