有时,C API可能需要NULL指针.
CGO有可能吗?
例如,我想在Go语言程序中将null参数传递给strcmp():
package strutil /* #include <stdlib.h> #include <string.h> */ import ( "C" "unsafe" ) func StrCmp(a,b string) int { pca := C.CString(a) defer C.free(pca) pcb := C.CString(b) defer C.free(pcb) ret := C.strcmp(pca,pcb) return int(ret) }
如果我将pca设置为nil,则会发生以下错误:
Exception 0xc0000005 0x0 0x0 0x76828b21 PC=0x76828b21 signal arrived during cgo execution strutil._Cfunc_strcmp(0x0,0x761b00,0x0) strutil/_obj/_cgo_gotypes.go:79 +0x49 strutil.StrCmp(0x19,0x10,0x4bbf38,0xa,0x1fbc1f98,0x0,0xffff,...)
那么,我怎样才能将NULL传递给strcmp?
谢谢
解决方法
如果你想将NULL传递给C函数,你可以简单地将nil传递给它.
但是,没有记录当您向函数strcmp(…)发送NULL指针时会发生什么.我猜你在向它传递NULL时strcmp失败了.最好先检查输入,并在其中一个输入设置为nil时返回错误.
package main /* #include <stdlib.h> #include <string.h> */ import "C" import ( "errors" "fmt" "unsafe" ) func StrCmp(a,b *string) (int,error) { if nil == a || nil == b { return 0,errors.New("Both strings have to be set") } pca := C.CString(*a) defer C.free(unsafe.Pointer(pca)) pcb := C.CString(*b) defer C.free(unsafe.Pointer(pcb)) ret := C.strcmp(pca,pcb) return int(ret),nil } func main() { left := "Left" right := "Right" fmt.Println(StrCmp(&left,&right)) fmt.Println(StrCmp(&left,&left)) fmt.Println(StrCmp(nil,nil)) }
如果需要一个示例如何将NULL传递给接受NULL指针的函数:
package main /* #include <stdio.h> int am_i_null(int* pointer) { if (NULL == pointer) { return -1; } return *pointer; } */ import "C" import ( "fmt" "unsafe" ) func main() { fmt.Println(C.am_i_null(nil)) var cInteger C.int = 8 fmt.Println(C.am_i_null(&cInteger)) var goInteger int = 7 fmt.Println(C.am_i_null((*C.int)(unsafe.Pointer(&goInteger)))) }