Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cgo: Converting []uchar to []byte #38002

Closed
elichai opened this issue Mar 22, 2020 · 1 comment
Closed

cgo: Converting []uchar to []byte #38002

elichai opened this issue Mar 22, 2020 · 1 comment

Comments

@elichai
Copy link

elichai commented Mar 22, 2020

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

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?

@ianlancetaylor
Copy link
Member

Unlike many projects, we don't use the issue tracker for questions. You will get better and faster answers on a forum. Please see https://golang.org/wiki/Questions. Thanks.

I don't know of a better way to do this than what you are already done. The interface between Go and C is imperfect.

@golang golang locked and limited conversation to collaborators Mar 22, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants