Skip to content

Instantly share code, notes, and snippets.

@poying
Last active Dec 5, 2017
Embed
What would you like to do?
play cgo
$ go run cmd/main.go
// cmd/main.go
package main

import (
	"github.com/poying/tmp/foo"
)

func main() {
	foo.Hello("poying")
}
// foo/foo.c
#include <stdio.h>
#include "foo.h"
#include "_cgo_export.h"

void *ACFunction(char *name) {
	//printf("ACFunction()\n");
	return AGoFunction(name);
} 
// foo/foo.h
#pragma once

extern void *ACFunction(char *name);
// foo/foo.go
package foo

// #include <stdlib.h>
// #include "foo.h"
import "C"
import (
	"fmt"
	"unsafe"
)

type Foo struct {
	Name string
}

func FreeFoo(foo *Foo) {
	C.free(unsafe.Pointer(foo))
}

//export AGoFunction
func AGoFunction(name *C.char) unsafe.Pointer {
	var foo Foo
	size := (C.size_t)(unsafe.Sizeof(foo))
	foop := (*Foo)(C.malloc(size))
	foop.Name = C.GoString(name)
	return unsafe.Pointer(foop)
}

func Hello(goname string) {
	name := C.CString(goname)
	foo := (*Foo)(C.ACFunction(name))
	C.free((unsafe.Pointer)(name))
	FreeFoo(foo)
	fmt.Printf("Hello %s\n", foo.Name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment