Skip to content

Commit

Permalink
cgo example
Browse files Browse the repository at this point in the history
  • Loading branch information
tlming16 committed Aug 27, 2020
1 parent 65d9316 commit 5a30818
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 0 deletions.
5 changes: 5 additions & 0 deletions go/goutil/cgo/hello.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# include "hello.h"

void hello(char *s){
printf("hello cgo! \n %s",s);
}
3 changes: 3 additions & 0 deletions go/goutil/cgo/hello.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# include <stdio.h>

void hello( char *s);
Binary file added go/goutil/cgo/libhello.dll
Binary file not shown.
59 changes: 59 additions & 0 deletions go/goutil/cgo/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# cgo

- 编译c函数为动态链接库

```
# include <stdio.h>
void hello( char *s);
```

```c
# include "hello.h"
void hello(char *s){
printf("hello cgo! \n %s",s);
}
```
- 编译成 动态链接库
```
gcc -shared -fPIC -o libhello.dll hello.c
```
- 编写 go main函数
```go
// test_hello.go
package main
/*
#cgo LDFLAGS: -L. -lhello
#include<stdio.h>
#include<stdlib.h>
#include"hello.h"
*/
import "C"
import (
"unsafe"
)
func main(){
s:=" hello\n";
cs:=C.CString(s);
C.hello(cs);
defer C.free(unsafe.Pointer(cs));
}
```

- 运行

```
go run test_hello.go
```

- https://golang.org/cmd/cgo/#hdr-C_references_to_Go



21 changes: 21 additions & 0 deletions go/goutil/cgo/test_hello.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

/*
#cgo LDFLAGS: -L. -lhello
#include<stdio.h>
#include<stdlib.h>
#include"hello.h"
*/
import "C"
import (
"unsafe"
)

func main(){
s:=" hello\n";
cs:=C.CString(s);
C.hello(cs);
defer C.free(unsafe.Pointer(cs));


}

0 comments on commit 5a30818

Please sign in to comment.