go-ptrloop

command module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 27, 2020 License: MIT Imports: 4 Imported by: 0

README

go-ptrloop

Go Report Card License MIT Go Doc Release

A helper to iterate over unsafe pointers.

Install

go get -u github.com/danielgatis/go-ptrloop

And then import the package in your code:

import "github.com/danielgatis/go-ptrloop/ptrloop"
Example

An example described below is one of the use cases.

package main

/*
#include <stdlib.h>
#include <strings.h>

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

Licensed under MIT License

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL