https://github.com/danielgatis/go-ptrloop
A helper to iterate over unsafe pointers.
https://github.com/danielgatis/go-ptrloop
c go golang pointer-arithmetic unsafe-pointers
Last synced: 11 months ago
JSON representation
A helper to iterate over unsafe pointers.
- Host: GitHub
- URL: https://github.com/danielgatis/go-ptrloop
- Owner: danielgatis
- License: mit
- Created: 2020-05-27T20:10:04.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2020-09-26T04:34:33.000Z (over 5 years ago)
- Last Synced: 2025-02-08T20:47:32.753Z (about 1 year ago)
- Topics: c, go, golang, pointer-arithmetic, unsafe-pointers
- Language: Go
- Homepage:
- Size: 6.84 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# go-ptrloop
[](https://goreportcard.com/report/github.com/danielgatis/go-ptrloop)
[](https://raw.githubusercontent.com/danielgatis/go-ptrloop/master/LICENSE)
[](https://godoc.org/github.com/danielgatis/go-ptrloop)
A helper to iterate over unsafe pointers.
## Install
```bash
go get -u github.com/danielgatis/go-ptrloop
```
And then import the package in your code:
```go
import "github.com/danielgatis/go-ptrloop/ptrloop"
```
### Example
An example described below is one of the use cases.
```go
package main
/*
#include
#include
char** createArray(int n) {
char** array = (char **) malloc(n * sizeof(char *));
for (int i = 0; i < n; ++i) {
array[i] = strdup("hello!");
}
return array;
}
*/
import "C"
import (
"fmt"
"unsafe"
"github.com/danielgatis/go-ptrloop/ptrloop"
)
func main() {
n := 3
array := C.createArray(C.int(n))
ptrloop.Loop(unsafe.Pointer(array), int(n), func(ptr unsafe.Pointer, i int) bool {
s := *(**C.char)(ptr)
fmt.Printf("%v -> %v\n", i, C.GoString(s))
return true
})
}
```
```
❯ go run main.go
0 -> hello!
1 -> hello!
2 -> hello!
```
## License
Copyright (c) 2020-present [Daniel Gatis](https://github.com/danielgatis)
Licensed under [MIT License](./LICENSE)