小编tan*_*bro的帖子

CGO,如何将NULL参数传递给C函数

有时,C API可能需要NULL指针.

CGO有可能吗?

例如,我想strcmp()在Go语言程序中传递一个null参数:

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)
}
Run Code Online (Sandbox Code Playgroud)

如果我设置pcanil,则会发生此错误:

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, 0x0, 0xffff, 0x0,     0x0, ...)
Run Code Online (Sandbox Code Playgroud)

那么,我怎样才能将NULL传递给strcmp?

谢谢

go null-pointer cgo

6
推荐指数
1
解决办法
5306
查看次数

标签 统计

cgo ×1

go ×1

null-pointer ×1