Hi,
I am trying to use CGO to call an optimized C++ CPU-bound implementation of a complex algorithms from golang. Basically, it will pass a string into c++ function and get a string back. A simplified version of the code can be seen in the below:
//algo.go
package main
//#cgo LDFLAGS:
//#include <stdio.h>
//#include <stdlib.h>
//#include <string.h>
//char* echo(char* s);
import "C"
import "unsafe"
func main() {
cs := C.CString("Hello from stdio\n")
defer C.free(unsafe.Pointer(cs))
var echoOut *C.char = C.echo(cs)
//defer C.free(unsafe.Pointer(echoOut)); -> using this will crash the code
fmt.Println(C.GoString(echoOut));
}
//algo.cpp
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <math.h>
using namespace std;
extern "C" {
char* echo(char* o) {
int len = sizeof(o) / sizeof(char);
char* out = (char*)malloc(len * sizeof(char));
strcpy(out, o);
return out;
}
}
Thanks.
PS: another side questions, my actual c++ function is something like: char* lsh_hash(char* text, char* vectors_key); whereas vectors_key is a big object. I am current using: cVectorsKey := C.CString(string(byte_arr)); and then get the data like: C.GoString(C.lsh_hash(cText, cVectorsKey)). I assume that it will only pass pointer into c++ function but want to double confirm if it's best way to handle long vector_key or I should somehow manage to set vector key inside c++ code as global variable to avoid passing data from go function into c++ function.