cgo: avoid '"unsafe" imported but not used' error

This can happen when not all CGo features are used.
Этот коммит содержится в:
Ayke van Laethem 2019-11-06 14:52:35 +01:00 коммит произвёл Ron Evans
родитель b41e58bcb4
коммит 913131bf62
3 изменённых файлов: 31 добавлений и 0 удалений

Просмотреть файл

@ -185,6 +185,7 @@ func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string
Name: files[0].Name.Name,
},
Decls: []ast.Decl{
// import "unsafe"
&ast.GenDecl{
TokPos: p.generatedPos,
Tok: token.IMPORT,
@ -192,6 +193,32 @@ func Process(files []*ast.File, dir string, fset *token.FileSet, cflags []string
unsafeImport,
},
},
// var _ unsafe.Pointer
// This avoids type errors when the unsafe package is never used.
&ast.GenDecl{
Tok: token.VAR,
Specs: []ast.Spec{
&ast.ValueSpec{
Names: []*ast.Ident{
&ast.Ident{
Name: "_",
Obj: &ast.Object{
Kind: ast.Var,
Name: "_",
},
},
},
Type: &ast.SelectorExpr{
X: &ast.Ident{
Name: "unsafe",
},
Sel: &ast.Ident{
Name: "Pointer",
},
},
},
},
},
},
Imports: []*ast.ImportSpec{unsafeImport},
}

2
cgo/testdata/basic.out.go предоставленный
Просмотреть файл

@ -2,6 +2,8 @@ package main
import "unsafe"
var _ unsafe.Pointer
type C.int16_t = int16
type C.int32_t = int32
type C.int64_t = int64

2
cgo/testdata/types.out.go предоставленный
Просмотреть файл

@ -2,6 +2,8 @@ package main
import "unsafe"
var _ unsafe.Pointer
const C.option2A = 20
const C.optionA = 0
const C.optionB = 1