Skip to content

Instantly share code, notes, and snippets.

@poying
Last active December 5, 2017 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poying/5e4898d1bfe68f192d470f87a75f552a to your computer and use it in GitHub Desktop.
Save poying/5e4898d1bfe68f192d470f87a75f552a to your computer and use it in GitHub Desktop.
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