1

I am using cgo and saw this post about running c++ from go:

I want to use [this function] in Go. I'll use the C interface

  // foo.h
  #ifdef __cplusplus
  extern "C" {
  #endif
   typedef void* Foo;
   Foo FooInit(void);
   void FooFree(Foo);
   void FooBar(Foo);
  #ifdef __cplusplus
  }
  #endif

I did this, but how can I pass a string as an argument to the C++ function? I tried to pass a rune[] but it did not work.

B--rian
  • 5,578
  • 10
  • 38
  • 89
Ank i zle
  • 2,089
  • 3
  • 14
  • 36
  • I assume you mean a nul-terminated string as in C and not some C++ string class. If so see https://github.com/golang/go/wiki/cgo#go-strings-and-c-strings – Andrew W. Phillips Feb 20 '20 at 07:07
  • I expanded your question with a quote from the reference you are citing. Hope that helps. – B--rian Feb 20 '20 at 10:30

1 Answers1

0

This is the Go code:

// GetFileSizeC wrapper method for retrieve byte lenght of a file
func GetFileSizeC(filename string) int64 {
    // Cast a string to a 'C string'
    fname := C.CString(filename)
    defer C.free(unsafe.Pointer(fname))
    // get the file size of the file
    size := C.get_file_size(fname)
    return int64(size)
}

From C

long get_file_size(char *filename) {
  long fsize = 0;
  FILE *fp;
  fp = fopen(filename, "r");
  if (fp) {
    fseek(fp, 0, SEEK_END);
    fsize = ftell(fp);
    fclose(fp);
  }
  return fsize;
}

Remember that you need to add the headers library that you need before the import in the Go file:

package utils

// #cgo CFLAGS: -g -Wall
// #include <stdio.h>   |
// #include <stdlib.h>  | -> these are the necessary system header
// #include <string.h>  |
// #include "cutils.h" <-- this is a custom header file
import "C"
import (
    "bufio"
    "encoding/json"
    "fmt"
    "io/ioutil"
     ....
)

This is an old project that you can use for future working example:

https://github.com/alessiosavi/GoUtils

alessiosavi
  • 2,753
  • 2
  • 19
  • 38
  • why do you call it as "cast" wherein it's literally a type conversation (which includes unnecessary (for this case) copy)? – Laevus Dexter Feb 20 '20 at 23:26
  • Hi @Laevus, i can't understand your point. In order to call the C code is necessary to convert (you are right, is not a cast) the string and then free the data. Why is unnecessary the copy? Could you provide a simple test ? – alessiosavi Feb 22 '20 at 09:19
  • ye, sorry, I forgot that string must be null terminated in that case. In the other one, i'd pass backing array pointer from the go's string – Laevus Dexter Feb 22 '20 at 13:21