dongxiangchan0743 2019-03-05 15:21
浏览 143

当返回指向包含指针的C结构的指针时,cgo出现恐慌

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 使用ESP8266连接阿里云出现问题
    • ¥15 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
    • ¥15 BP神经网络控制倒立摆
    • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
    • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
    • ¥30 Unity接入微信SDK 无法开启摄像头
    • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
    • ¥20 cad图纸,chx-3六轴码垛机器人
    • ¥15 移动摄像头专网需要解vlan
    • ¥20 access多表提取相同字段数据并合并