-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathcgo.go
More file actions
42 lines (37 loc) · 991 Bytes
/
cgo.go
File metadata and controls
42 lines (37 loc) · 991 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Copyright 2015 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cgo tests bindings of CGo-based packages.
package cgo
//#include <stdio.h>
//#include <string.h>
//#include <stdlib.h>
//const char* cpkg_sprintf(const char *str) {
// char *o = (char*)malloc(strlen(str) + 1);
// sprintf(o, "%s", str);
// return o;
//}
import "C"
import (
"fmt"
"unsafe"
)
// Hi returns a string from Go (via C's stdio)
func Hi() string {
cstr := C.CString("hi from go\n")
defer C.free(unsafe.Pointer(cstr))
cout := C.cpkg_sprintf(cstr)
defer C.free(unsafe.Pointer(cout))
return C.GoString(cout)
}
// Hello returns a string via C's stdio
func Hello(s string) string {
if s == "" {
s = "you"
}
cstr := C.CString(fmt.Sprintf("hello %s from go\n", s))
defer C.free(unsafe.Pointer(cstr))
cout := C.cpkg_sprintf(cstr)
defer C.free(unsafe.Pointer(cout))
return C.GoString(cout)
}