Initial commit

This commit is contained in:
Victor Timofei 2022-07-29 21:45:20 +03:00
commit 14e763c65a
Signed by: vtimofei
GPG Key ID: B790DCEBE281403A
7 changed files with 90 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
cgo-callback
mylib.o

13
Makefile Normal file
View File

@ -0,0 +1,13 @@
GO=go
.PHONY: all
all: cgo-callback
mylib.o: mylib.c
cgo-callback: mylib.o mylib.h
$(GO) build
.PHONY: clean
clean:
rm -f mylib.o cgo-callback

13
cfuncs.go Normal file
View File

@ -0,0 +1,13 @@
package main
/*
#include <stdio.h>
void callOnMeGo_cgo(int n)
{
printf("callOnMeGo_cgo called\n");
void callOnMeGo(int);
callOnMeGo(n);
}
*/
import "C"

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.vtimothy.com/vtimofei/cgo-callback
go 1.18

45
main.go Normal file
View File

@ -0,0 +1,45 @@
package main
import (
"fmt"
"sync"
"unsafe"
)
/*
#cgo CFLAGS: -I .
#cgo LDFLAGS: -L .
#include "mylib.h"
void callOnMeGo_cgo(int n);
*/
import "C"
//export callOnMeGo
func callOnMeGo(n int) {
printerCallback(n)
}
type Printer func(int)
var printerCallback Printer
var printerCallbackLock sync.RWMutex
func usePrinter(p Printer) {
printerCallbackLock.Lock()
printerCallback = p
C.use_printer((C.printer_t)(unsafe.Pointer(C.callOnMeGo_cgo)))
printerCallback = nil
printerCallbackLock.Unlock()
}
var myPrinter Printer = Printer(func(n int) {
for i := 0; i < n; i++ {
fmt.Printf("%d\n", i)
}
})
func main() {
usePrinter(myPrinter)
}

6
mylib.c Normal file
View File

@ -0,0 +1,6 @@
#include "mylib.h"
void use_printer(printer_t p)
{
p(14);
}

8
mylib.h Normal file
View File

@ -0,0 +1,8 @@
#ifndef MYLIB_H
#define MYLIB_H 1
typedef void (*printer_t)(int);
void use_printer(printer_t);
#endif