Providing an interop example for Golang (#16)

This commit is contained in:
Ivan Folgueira Bande 2023-06-27 08:09:38 +02:00 committed by GitHub
parent 38645857dc
commit 6dde1b0292
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 59 additions and 0 deletions

View File

@ -1,3 +1,4 @@
main-c
main-rs
main-go
libasynclib.a

View File

@ -6,5 +6,9 @@ main-rs: asynclib.nim main.rs
nim c --debuginfo --app:staticlib --noMain asynclib
rustc main.rs -L. -lasynclib -o main-rs
main-go: asynclib.nim main.go
nim c --debuginfo --app:staticlib --noMain asynclib
go build -o main-go main.go
prepare:
nimble install -y chronos

54
interop/async/main.go Normal file
View File

@ -0,0 +1,54 @@
package main
/*
#cgo LDFLAGS: -L./ -lasynclib
#include <stdio.h>
// Import functions from Nim
void* startNode(const char* url, void* onHeader, void* user);
void stopNode(void** ctx);
typedef const char cchar_t;
extern void callback(void* user, cchar_t* headers, size_t len);
*/
import "C"
import (
"fmt"
"runtime"
"unsafe"
)
//export callback
func callback(user *C.void, headers *C.cchar_t, len C.size_t) {
fmt.Println("Callback! ", uint64(len))
fmt.Println(C.GoStringN(headers, C.int(len)))
}
func main() {
runtime.LockOSThread()
fmt.Println("Starting node")
user := 23
ctx := C.startNode(C.CString("127.0.0.1:60000"),
unsafe.Pointer(C.callback),
unsafe.Pointer(&user))
fmt.Println(`
Node is listening on http://127.0.0.1:60000
Type 'q' and press enter to stop
`)
for {
if C.getchar() == 'q' {
break
}
}
fmt.Println("Stopping node")
C.stopNode(&ctx)
}