猿问

CGO中的C NULL类型

我有一个 C 函数,它在发生异常时返回 NULL。我如何在 Go 中检查返回值是否为 NULL,因为它没有内置类型来表示 C NULL。下面是我的代码


retVal := C.myfunc()


if retVal == nil {

  // handle the error

}


慕容3067478
浏览 178回答 1
1回答

慕桂英4014372

我认为您可以用来nil测试 c 函数是否返回NULL. 试试下面的代码:package main/*#include <stdio.h>#include <stdlib.h>int* cfunc(int i) {&nbsp; &nbsp; if (i == 0) {&nbsp; &nbsp; &nbsp; &nbsp; return NULL;&nbsp; &nbsp; }&nbsp; &nbsp; int *p = (int*)malloc(sizeof(int));&nbsp; &nbsp; *p = 100;&nbsp; &nbsp; return p;}*/import "C"import "fmt"import "unsafe"func call_cfunc(i int32) {&nbsp; &nbsp; ret := C.cfunc(C.int(i))&nbsp; &nbsp; if ret == nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("nil")&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(*ret)&nbsp; &nbsp; &nbsp; &nbsp; C.free(unsafe.Pointer(ret))&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; call_cfunc(0)&nbsp; &nbsp; call_cfunc(1)}
随时随地看视频慕课网APP

相关分类

Go
我要回答