cgo: Converting `[]uchar` to `[]byte`

Hi,
First of all, cgo is pretty cool, thanks for that :slight_smile:

I do have a question though, I have a lot of C structs that just contain a byte array, and I want to use the array in it as a []byte. ie:

typedef struct {
    unsigned char data[64];
} pubkey;

I would like to be able to then do:

type SchnorrPublicKey struct {
	pubkey C.pubkey
}

func (key *SchnorrPublicKey) String() string {
	return hex.EncodeToString(key.pubkey.data[:])
}

But I get the following error:
./schnorr.go:39:43: cannot use key.pubkey.data[:] (type []_Ctype_uchar) as type []byte in argument to hex.EncodeToString
I can get this working by doing something like:
return hex.EncodeToString(C.GoBytes(unsafe.Pointer(&key.pubkey.data[0]), C.int(len(key.pubkey.data))))

But it feels kinda stupid, it’s a lot of complexity to convert an already go slice into another go slice just to replace the _Ctype_uchar type with byte type, and they are 100% compatible anyway.

Is there a better way to do this?

Hi, @elichai, try casting through unsafe.Pointer:

type SchnorrPublicKey struct {
	pubkey C.pubkey
}

func (key *SchnorrPublicKey) String() string {
    pk := *((*[64]byte)(unsafe.Pointer(&key.pubkey)))
    return hex.EncodeToString(pk[:])
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.