CGO -- need a null pointer

3,932 views
Skip to first unread message

Hans Stimer

unread,
Oct 14, 2010, 12:04:12 AM10/14/10
to golang-nuts
I have a C library function that takes a char * which can optionally
be null. My go wrapper checks for the empty string and if so it passes
null to the c routine. Well it would if I could get this to compile:

func BoardOpen(handle int, clientAddress, remoteAddress string) int {
var pClient unsafe.Pointer
if clientAddress == "" {
pClient = (unsafe.Pointer) (0)
} else {
pClient = C.CString(clientAddress)
}

pRemote := C.CString(remoteAddress)

err := C.Open((C.u32) (handle), pClient, pRemote);

return (int)(err)
}

unsafe.Pointer(0) can't turn 0 into a pointer

What is the right way to right this?

Alec Thomas

unread,
Oct 14, 2010, 12:20:35 AM10/14/10
to Hans Stimer, golang-nuts
I believe you can simply pass "nil" to your function.

--
I think I see the problem. The problem is that you are wrong.

Steven

unread,
Oct 14, 2010, 12:22:46 AM10/14/10
to Hans Stimer, golang-nuts
0 is assumed to be of type "int", since its type cannot otherwise be determined by the context. An int cannot be converted to unsafe.Pointer. In go, 'nil' is used to denote a null (nil) pointer, so p = nil works. You can also explicitly cast to uintptr, which can be converted to unsafe.Pointer ("unsafe.Pointer(uintptr(0))").

As a final note, pClient is initialized to nil to begin with, so the assignment is redundant.
Reply all
Reply to author
Forward
0 new messages