Skip to content

Instantly share code, notes, and snippets.

@bryanjhv
Created June 22, 2023 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanjhv/d6c5da70e48b11ff22cefb30c4407d75 to your computer and use it in GitHub Desktop.
Save bryanjhv/d6c5da70e48b11ff22cefb30c4407d75 to your computer and use it in GitHub Desktop.
/*
An example that converts os.Args to argc/argv for C.
Can be used with any []string with the same procedure.
*/
package main
/*
#include <stdio.h>
#include <stdlib.h>
void print_argv(int argc, char** argv) {
for (int i = 0; i < argc; i++)
printf("%d: %s\n", i, argv[i]);
}
*/
import "C"
import (
"os"
"runtime"
"unsafe"
)
func main() {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
args := make([]*C.char, len(os.Args))
for i, arg := range os.Args {
args[i] = C.CString(arg)
defer C.free(unsafe.Pointer(args[i]))
}
argc := C.int(len(args))
argv := (**C.char)(unsafe.Pointer(&args[0]))
C.print_argv(argc, argv)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment