Passing array of string as parameter from go to C function - go

I have one C function:
int cgroup_change_cgroup_path(const char * path, pid_t pid, const char *const controllers[])
I want to call it in go language by using cgo.
How to pass the third parameter as it accepts a C array of string.

You can build the arrays using c helper functions and then use them.
Here is a solution to the same problem:
// C helper functions:
static char**makeCharArray(int size) {
return calloc(sizeof(char*), size);
}
static void setArrayString(char **a, char *s, int n) {
a[n] = s;
}
static void freeCharArray(char **a, int size) {
int i;
for (i = 0; i < size; i++)
free(a[i]);
free(a);
}
// Build C array in Go from sargs []string
cargs := C.makeCharArray(C.int(len(sargs)))
defer C.freeCharArray(cargs, C.int(len(sargs)))
for i, s := range sargs {
C.setArrayString(cargs, C.CString(s), C.int(i))
}
golangnuts post by John Barham

Related

Convert *_Ctype_float into float32 in Go

I am new to Go and having difficulty in converting the *_Ctype_float datatype into []float32. Is there something that I am missing? I even thought of converting *_Ctype_float into string but even that was not successful.
I have this C function named predictInstance which returns float*. I am calling this function from Go by
predictionValues := C.predictInstance(
handle,
(*C.float)(unsafe.Pointer(&req.FlatInput[0])),
)
Now when I look at the type of predictionValues it says it is *Ctype_float. Now I want to convert this into []float32
I have a C function which returns a float* array which I wish to convert to []float32. I am calling this
function from Go with a float* array argument.
A working example,
package main
/*
#include <stdlib.h>
#include <float.h>
float *reverse(float *f, int len) {
float *g = calloc(len, sizeof(float));
for (int i = 0; i < len; i++) {
g[i] = f[len-1-i];
}
return g;
}
*/
import "C"
import (
"fmt"
"math"
"unsafe"
)
func main() {
a := []float32{3.14159, 2.718, 1}
r := make([]float32, len(a))
fmt.Println("a:", a, "r:", r)
c := C.reverse((*C.float)(&a[0]), C.int(len(a)))
copy(r, (*[1 << 20]float32)(unsafe.Pointer(c))[:])
C.free(unsafe.Pointer(c))
fmt.Println("a:", a, "r:", r)
}
var okCFloat = func() bool {
if C.sizeof_float != unsafe.Sizeof(float32(0)) {
panic("C float != Go float32")
}
if C.FLT_MAX != math.MaxFloat32 {
panic("C float != Go float32")
}
return true
}()
Output:
a: [3.14159 2.718 1] r: [0 0 0]
a: [3.14159 2.718 1] r: [1 2.718 3.14159]

Runtime error with cgo and certain string slices

I have stripped back a problem I have come across whilst wrapping some C code to work with golang using swig but the problem doesn't rest with swig.
I can pass in a basic string slice but as soon as I construct the slice with anything other than basic strings, I get a panic: runtime error: cgo argument has Go pointer to Go pointer.
go version go1.8.5 linux/amd64
This is the sample code and its output
package main
import (
"fmt"
"reflect"
"unsafe"
)
/*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { char *p; int n; } _gostring_;
typedef struct { void* array; int len; int cap; } _goslice_;
void prtText(char * const *txt, int len)
{
int i = 0;
for ( i=0; i<len; i++ ) {
printf("Text %d is: %s\n", i, txt[i]);
}
}
void _wrap_printText(_goslice_ _swig_go_0) {
_gostring_ *p;
char **arg1 = (char **)calloc(_swig_go_0.len, sizeof(char*));
if (arg1) {
for (int i=0; i<_swig_go_0.len; i++) {
p = &(((_gostring_*)_swig_go_0.array)[i]);
arg1[i] = calloc(1,(p->n)+1);
strncpy(arg1[i], p->p, p->n);
}
}
int arg2 = _swig_go_0.len;
prtText((char *const *)arg1,arg2);
}
*/
import "C"
func PrintText(arg1 []string) {
C._wrap_printText(*(*C._goslice_)(unsafe.Pointer(&arg1)))
}
func main() {
s := []string{}
s = append(s, "blah")
s = append(s, "hello")
s = append(s, "again")
ns := []string{}
ns = append(ns, "ns: "+s[0])
ns = append(ns, "ns: "+s[1])
ns = append(ns, "ns: "+s[2])
fmt.Println("type s:", reflect.TypeOf(s))
fmt.Println("type ns:", reflect.TypeOf(ns))
fmt.Println("s:", s)
fmt.Println("ns:", ns)
PrintText(s)
PrintText(ns)
}
go build -i -x -gcflags '-N -l' main.go
./main
type s: []string
type ns: []string
s: [blah hello again]
ns: [ns: blah ns: hello ns: again]
Text 0 is: blah
Text 1 is: hello
Text 2 is: again
panic: runtime error: cgo argument has Go pointer to Go pointer
As you can see, the first string slice works fine but as soon as I do anything other than basic strings, it fails. I've tried making new strings first before appending them to the slice but the problem remains.
What am I doing wrong?
You're basically passing the raw Go pointers.
Instead, you should build C arrays yourself.
As a general rule, seeing unsafe pretty much anywhere should make you suspicious. It is rarely the right way around issues with cgo.
Using the helpers from Passing array of string as parameter from go to C function and using them in your code:
package main
import (
"fmt"
"reflect"
)
/*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void prtText(char * const *txt, int len)
{
int i = 0;
for ( i=0; i<len; i++ ) {
printf("Text %d is: %s\n", i, txt[i]);
}
}
static char**makeCharArray(int size) {
return calloc(sizeof(char*), size);
}
static void setArrayString(char **a, char *s, int n) {
a[n] = s;
}
static void freeCharArray(char **a, int size) {
int i;
for (i = 0; i < size; i++)
free(a[i]);
free(a);
}
*/
import "C"
func main() {
s := []string{}
s = append(s, "blah")
s = append(s, "hello")
s = append(s, "again")
ns := []string{}
ns = append(ns, "ns: "+s[0])
ns = append(ns, "ns: "+s[1])
ns = append(ns, "ns: "+s[2])
fmt.Println("type s:", reflect.TypeOf(s))
fmt.Println("type ns:", reflect.TypeOf(ns))
fmt.Println("s:", s)
fmt.Println("ns:", ns)
sargs := C.makeCharArray(C.int(len(s)))
defer C.freeCharArray(sargs, C.int(len(s)))
for i, p := range s {
C.setArrayString(sargs, C.CString(p), C.int(i))
}
nsargs := C.makeCharArray(C.int(len(ns)))
defer C.freeCharArray(nsargs, C.int(len(ns)))
for i, p := range ns {
C.setArrayString(nsargs, C.CString(p), C.int(i))
}
C.prtText(sargs, C.int(len(s)))
C.prtText(nsargs, C.int(len(ns)))
}
The output is now as expected:
$ ./main
type s: []string
type ns: []string
s: [blah hello again]
ns: [ns: blah ns: hello ns: again]
Text 0 is: blah
Text 1 is: hello
Text 2 is: again
Text 0 is: ns: blah
Text 1 is: ns: hello
Text 2 is: ns: again

what's difference betwen int ch vs char ch

why for in following function used 't' for int ch"?
ch is int, why use char?
Synopsis:
#include <stdio.h>
char *strrchr(char *string, int c);
Example:
#include <stdio.h>
int main() {
char *s;
char buf [] = "This is a testing";
s = strrchr (buf, 't');
if (s != NULL)
printf ("found a 't' at %s\n", s);
return 0;
}

integer division in Go called from C

I am able to perform integer division in go by this program :
package main
import "fmt"
func main() {
a := 10
b := 5
fmt.Println(a/b)
}
Then I made a program in go that has functions for +, -, * and /.
and I made a program in C that calls each of these functions and performs arithmetic operations.
Except division, the code works fine.
The go file with the functions is : (calc.go)
package main
func Add(a, b int) int {
return a + b
}
func Sub(a, b int) int {
return a - b
}
func Mul(a, b int) int {
return a * b
}
func Div(a, b int) int {
return a / b
}
And the C program that calls these functions is : (calcc.c)
#include <stdio.h>
extern int go_add(int, int) __asm__ ("main.Add");
extern int go_sub(int, int) __asm__ ("main.Sub");
extern int go_mul(int, int) __asm__ ("main.Mul");
extern int go_div(int, int) __asm__ ("main.Div");
int menu()
{
int op;
printf("\n1 add");
printf("\n2 sub");
printf("\n3 mul");
printf("\n4 div");
printf("\nEnter your choice : ");
scanf("%d", &op);
return op;
}
int main() {
int op, ch, result, a, b;
do{
op= menu();
printf("First number : ");
scanf("%d", &a);
printf("Second number : ");
scanf("%d", &b);
switch(op)
{
case 1:
result = go_add(a, b);
printf("Result : %d" , result);
break;
case 2:
result = go_sub(a, b);
printf("Result : %d" , result);
break;
case 3:
result = go_mul(a, b);
printf("Result : %d" , result);
break;
case 4:
result = go_div(a, b);
printf("Result : %d" , result);
break;
default:
printf("Invalid choice ! ");
}
printf("\nAnother operation? (1 if yes) : ");
scanf("%d", &ch);
} while(ch==1);
printf("\nThank you!");
}
I compiled on the terminal using the commands :
gccgo -c calc.go
and
gcc calc.o calcc.c -o main
And got this error :
undefined reference to `__go_runtime_error'
collect2: error: ld returned 1 exit status
How should I fix this?
You need to link using gccgo and not with normal gcc. Normal gcc doesn't know that it ought to link against the go runtime (libgo).
Depending on your configuration, you might also need to specify where the runtime library can be found. For example by embedding it statically or by making it available in the LD_LIBRARY_PATH environment variable.
Example:
gccgo -static-libgo calc.o calcc.o -o main
For more information, check Setting up and using gccgo.
I believe your method of using __asm__ is gccgo specific (I've never seen it before).
The standard way to export Go functions to C is via an "//export name" comment in the Go code.
Further, standard Go<->C via cgo requires that C code is linked into Go and Go's main runs and not the other way around. This is so that the Go runtime is fully running. Otherwise goroutines, the garbage collector, etc would not be running. Of course Go's main could just be a simple call to a C pseudo-main function that does all the work and calls back into Go only as needed.
Given these points a small example of what you tried using standard cgo and fully go build-able is this:
calc.go:
package main
// /* could be in a declared in a header file instead */
// extern void pseudo_main(void);
import "C"
//export Add
func Add(a, b int) int {
return a + b
}
// … etc …
//export Div
func Div(a, b int) int {
return a / b
}
// Main needs to be Go so that the go runtime
// gets started so you can use goroutines, the
// garbage collector, etc,etc.
//
// It can just be a trivial call into a C main like
// function.
func main() {
C.pseudo_main()
}
and calc.c:
#include <stdio.h>
#include "_cgo_export.h" // file auto-generated by cgo from Go's "//export func" comments
// passing argc, argv, envp like arguments
// if desired is left as an excersise :)
void pseudo_main(void) {
int x, y, z;
printf("Hello from C\n");
x = 42;
y = 6;
z = Add(x, y);
printf("%d + %d = %d\n", x, y, z);
z = Div(x, y);
printf("%d / %d = %d\n", x, y, z);
}
building and running (on a Unix like host):
% go build -o calc
% ./calc
Note: normally you wouldn't use -o, you'd let the tool pick the name based on package or directory name. I've used -o here to list exact and repeatable commands without specifying what directory the files are in. Further note, for Microsoft Windows it would be different. Also, if you're interested in what goes on behind the scenes with cgo, try go build -x.
output:
Hello from C
42 + 6 = 48
42 / 6 = 7
gist.github.com
See also: The Go Blog: C? Go? Cgo!

Returning values through the arguments of go function, which is called from C

Suppose, we've got a Go function, which is doing something with agruments, passed to them, e.g. it could fill the buffer, allocated in the C part and changing it and for example an integer argument, which is a size of read data. It works well with an integer one, but not with a "data part". Just see a code.
package main
/*
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
extern int some(uint8_t *, int *);
static int somewrap() {
uint8_t *i = malloc(16);
int A = 1;
int *x = &A;
some(i, x);
fprintf(stderr, "c.wrapper, i=%s, %p, x=%d, %p\n", i, i, *x, x);
return 0;
}
*/
import "C"
import "fmt"
import (
"unsafe"
)
//export some
func some(i *C.uint8_t, x *C.int) C.int {
fmt.Println("i:", i, &i, *i, "x:", x, &x, *x)
p := []byte("xxx")
i = (*C.uint8_t)(unsafe.Pointer(&p[0]))
*x = C.int(42)
fmt.Println("i:", i, &i, *i, "x:", x, &x, *x)
return C.int(0)
}
func main() {
C.somewrap()
}
As a result, we've got following:
i: 0x4303a40 0xc210000018 0 x: 0x7fff5fbff874 0xc210000020 1
i: 0xc210000038 0xc210000018 120 x: 0x7fff5fbff874 0xc210000020 42
c.wrapper, i=, 0x4303a40, x=42, 0x7fff5fbff874
As you can see, it works well for integer pointer, but not for uint8_t.
You're re-assigning i within some to another address, not change the value at the given address (unless I'm misunderstanding what you're trying to accomplish)
*i = *(*C.uint8_t)(unsafe.Pointer(&p[0]))

Resources