I'm trying to build a small library written on Go for use with luajit. I can properly get what I want, until the struct which I return a pointer to contains pointers itself.
Go source:
package main
//typedef struct {
// int myint;
// double mydouble;
// char* mystring;
//} mystruct;
import "C"
import "fmt"
var myvar C.mystruct
//export Init
func Init() {
myvar.myint = 1
myvar.mydouble = 2.0
myvar.mystring = C.CString("three")
fmt.Println("myvar in go : ", myvar.myint, myvar.mydouble, myvar.mystring)
}
//export GetVar
func GetVar() *C.mystruct {
return &myvar
}
func main () {}
Lua source:
#! /usr/bin/luajit
local ffi = require("ffi")
local go = ffi.load("./golua.lib")
ffi.cdef[[
typedef struct {
int myint;
double mydouble;
char* mystring;
} mystruct;
extern void Init();
extern mystruct* GetVar();
]]
go.Init()
local var = go.GetVar()
print("myvar in lua : ", var.myint, var.mydouble, ffi.string(var.mystring))
Got this at runtime:
lionel@pc-lionel:~/go/src/tests/lua$ go build -buildmode=c-shared -o golua.lib *.go
lionel@pc-lionel:~/go/src/tests/lua$ ./gotest.lua
myvar in go : 1 2 0x55c17f41c360
panic: runtime error: cgo result has Go pointer
goroutine 17 [running, locked to thread]:
main._cgoexpwrap_86693eaa8e33_GetVar.func1(0xc420056ea8)
_cgo_gotypes.go:95 +0x3c
main._cgoexpwrap_86693eaa8e33_GetVar(0x7ff15cccac60)
_cgo_gotypes.go:97 +0x5b
Abandon (core dumped)
Note that the type of pointer does not matter, could be int* or whatever, it panics same way. I've also tried with GetVar returning an unsafe.Pointer instead with exact same result. In the example above I do not even need to assign a C.CString to mystring, cgo panics anyway.
For the purpose of my project, those C structures do not need to be modified on the lua side, especially not the strings, but need to be natively accessed for performance reasons.