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

Can we use Go generics to refine some of the utilities for reading C types #60

Open
brianmcgee opened this issue Aug 1, 2024 · 2 comments
Labels
enhancement New feature or request

Comments

@brianmcgee
Copy link
Member

brianmcgee commented Aug 1, 2024

We have a few methods for reading arrays from C. They are all identical except for the return type.

Can we use generics to combine them?

func ReadStringList(list *C.str_list_t) (result []string) {
for entry := list; entry != nil; entry = entry.next {
result = append(result, C.GoString(entry.str))
}
return result
}
func ReadUint64Array(arr unsafe.Pointer, length int) []uint64 {
start := uintptr(arr)
result := make([]uint64, length)
for i := range result {
next := start + uintptr(i*C.sizeof_uint64_t)
result[i] = *((*uint64)(unsafe.Pointer(next)))
}
return result
}
func ReadUintArray(arr unsafe.Pointer, length int) []uint {
start := uintptr(arr)
result := make([]uint, length)
for i := range result {
next := start + uintptr(i*C.sizeof_uint)
result[i] = *((*uint)(unsafe.Pointer(next)))
}
return result
}
func ReadIntArray(arr unsafe.Pointer, length int) []int {
// TODO see if we can use generics to combine some of these methods
start := uintptr(arr)
result := make([]int, length)
for i := range result {
next := start + uintptr(i*C.sizeof_uint)
result[i] = *((*int)(unsafe.Pointer(next)))
}
return result
}
func ReadByteArray(arr unsafe.Pointer, length int) []byte {
start := uintptr(arr)
result := make([]byte, length)
for i := range result {
next := start + uintptr(i*C.sizeof_uint)
result[i] = *((*byte)(unsafe.Pointer(next)))
}
return result
}

@brianmcgee brianmcgee added the enhancement New feature or request label Aug 1, 2024
@brianmcgee
Copy link
Member Author

@Mic92 recommends looking for unsafe slice, you can give it a pointer and a length.

@Mic92
Copy link
Member

Mic92 commented Aug 1, 2024

For strings you need to keep your function for the rest you could make a generic method with a type flag T that creates an unsafe slice and than copy the contents to a slice of type T

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
Status: No status
Development

No branches or pull requests

2 participants