2017-03-09 14 views
0

Calling Go Functions from Other Languagesにコードを拡張しようとしています。私はエラーを返す関数をどのように扱うことができるかを見たいと思います。以下のコードを参照してください。私はpanic: runtime error: invalid memory address or nil pointer dereferenceをPythonコードを実行するときに取得します。どのようにこれを修正するための任意のアイデア?PythonからGoを呼び出すときに「無効なメモリアドレス」

gmath.go

package main 

import (
    "fmt" 
) 

import "C" 

//export Div 
func Div(x, y float64) (float64, error) { 
    fmt.Printf("Div called: x=%f, y=%f\n", x, y) 
    if y == 0 { 
     return 0, fmt.Errorf("ZeroDivisionError") 
    } 
    return x/y, nil 
} 

func main() {} 

gmath.py

import ctypes 


class GoInterface(ctypes.Structure): 
    _fields_ = [ 
     ('t', ctypes.c_void_p), 
     ('v', ctypes.c_void_p), 
    ] 


class DivRet(ctypes.Structure): 
    _fields_ = [ 
     ('result', ctypes.c_float), 
     ('error', GoInterface), 
    ] 


lib = ctypes.cdll.LoadLibrary('./gmath.so') 
lib.Div.argtypes = [ctypes.c_double, ctypes.c_double] 
lib.Div.restype = DivRet 

r = lib.Div(1.2, 2.3) 

例それはのエラー部分と思わ

$ make 
go build -o gmath.so -buildmode=c-shared gmath.go 
$ python gmath.py 
Div called: x=1.200000, y=2.300000 
panic: runtime error: invalid memory address or nil pointer dereference 
[signal SIGSEGV: segmentation violation code=0x1 addr=0x17 pc=0x7fbe5fda928d] 

goroutine 17 [running, locked to thread]: 
main._cgoexpwrap_448ea9090bef_Div.func1(0xc42003cea8) 
    command-line-arguments/_obj/_cgo_gotypes.go:46 +0x42 
main._cgoexpwrap_448ea9090bef_Div(0x3ff3333333333333, 0x4002666666666666, 0x3fe0b21642c8590b, 0x0, 0x0) 
    command-line-arguments/_obj/_cgo_gotypes.go:48 +0xaa 
[1] 29009 abort (core dumped) python gmath.py 

答えて

1

実行結果が最初の問題です。エラーを文字列に変更して(float64、* C.char)を返すと、それは動作します。

+0

https://groups.google.com/forum/#!topic/golang-nuts/xOqrJjS7-xEも参照してください – lazy1

関連する問題