tan*_*bro 6 go null-pointer cgo
有时,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)
如果我设置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, 0x0, 0xffff, 0x0, 0x0, ...)
Run Code Online (Sandbox Code Playgroud)
那么,我怎样才能将NULL传递给strcmp?
谢谢
San*_*der 10
如果你想将NULL传递给C函数,你可以简单地传入nil
它.
但是,没有记录当您向函数发送NULL指针时会发生什么strcmp(...)
.我猜你在向它传递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, &right))
fmt.Println(StrCmp(&left, nil))
}
Run Code Online (Sandbox Code Playgroud)
如果需要一个示例如何将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))))
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5306 次 |
最近记录: |