Skip to content

Commit

Permalink
capi: fix sample Golang client (#1956)
Browse files Browse the repository at this point in the history
Fix the init settings in our Go sample code using the C API library and improve error handling.
  • Loading branch information
canepat authored Apr 9, 2024
1 parent 4b14186 commit 98447ef
Showing 1 changed file with 37 additions and 7 deletions.
44 changes: 37 additions & 7 deletions cmd/capi/sample-go-client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,51 @@ package main
// #cgo LDFLAGS: -L${SRCDIR}/../../../build/silkworm/capi
// #cgo LDFLAGS: -Wl,-rpath ${SRCDIR}/../../../build/silkworm/capi
// #cgo CFLAGS: -I${SRCDIR}/../../../silkworm/capi
// #include "silkworm.h"
/*
#include "silkworm.h"
#include <stdlib.h>
#include <string.h>
static bool go_string_copy(_GoString_ s, char *dest, size_t size) {
size_t len = _GoStringLen(s);
if (len >= size) return false;
const char *src = _GoStringPtr(s);
strncpy(dest, src, len);
dest[len] = '\0';
return true;
}
*/
import "C"

import "fmt"
import "os"

func main() {
dataDirPath := os.Getenv("HOME")
libMdbxVersion := C.GoString(C.silkworm_libmdbx_version())

var handle C.SilkwormHandle
settings := &C.struct_SilkwormSettings{}
if C.silkworm_init(&handle, settings) != C.SILKWORM_OK {
fmt.Fprintln(os.Stderr, "silkworm_init failed")
return
if !C.go_string_copy(dataDirPath, &settings.data_dir_path[0], C.SILKWORM_PATH_SIZE) {
fmt.Fprintln(os.Stderr, "silkworm.New failed to copy dataDirPath")
os.Exit(1)
}
if !C.go_string_copy(libMdbxVersion, &settings.libmdbx_version[0], C.SILKWORM_GIT_VERSION_SIZE) {
fmt.Fprintln(os.Stderr, "silkworm.New failed to copy libMdbxVersion")
os.Exit(2)
}
if C.silkworm_fini(handle) != C.SILKWORM_OK {
fmt.Fprintln(os.Stderr, "silkworm_fini failed")
return

initResult := C.silkworm_init(&handle, settings)
if initResult != C.SILKWORM_OK {
fmt.Fprintln(os.Stderr, "silkworm_init failed:", initResult)
os.Exit(int(initResult))
}

finiResult := C.silkworm_fini(handle)
if finiResult != C.SILKWORM_OK {
fmt.Fprintln(os.Stderr, "silkworm_fini failed:", finiResult)
os.Exit(int(finiResult))
}

os.Exit(0)
}

0 comments on commit 98447ef

Please sign in to comment.