Use GoString in C

I am trying to use some Go code in a C program thanks to cgo

My Go file looks like this:

package hello

import (
    "C"
)

//export HelloWorld
func HelloWorld() string{
    return "Hello World"
}

      

And my C code is something like this:

#include "_obj/_cgo_export.h"
#include <stdio.h>

int main ()
{
   GoString greeting = HelloWorld();

   printf("Greeting message: %s\n", greeting.p );

   return 0;
}

      

But what I get as output is not what I expected:

Welcome message:

I assume this is an encoding issue, but there is very little documentation and I know almost nothing about C.

Do you know what went wrong in this code?

Edit:

As I just said in the comment below:

I [...] tried to return and print only Go int (which is C "long long") and got wrong value.

So it seems like my problem is not string encoding or null termination but probably with the way I compile the whole thing

I will add all my compilation steps soon

+3


source to share


2 answers


My problem is well described in this comment: Calling go function from C

You can call Go code from C, but at the moment you cannot embed the Go runtime in a C application, which is an important but subtle difference.



What I was trying to do and why it failed.

I will now consider a new option-buildmode=c-shared

0


source


printf

expects a null-terminated string, but Go strings are not NUL-terminated, so your C program exhibits undefined behavior. Instead, do the following:

#include "_obj/_cgo_export.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
   GoString greeting = HelloWorld();

   char* cGreeting = malloc(greeting.n + 1);
   if (!cGreeting) { /* handle allocation failure */ }
   memcpy(cGreeting, greeting.p, greeting.n);
   cGreeting[greeting.n] = '\0';

   printf("Greeting message: %s\n", cGreeting);

   free(cGreeting);

   return 0;
}

      

or



#include "_obj/_cgo_export.h"
#include <stdio.h>

int main() {
    GoString greeting = HelloWorld();

    printf("Greeting message: ");
    fwrite(greeting.p, 1, greeting.n, stdout);
    printf("\n");

    return 0;
}

      

or of course:

func HelloWorld() string {
    return "Hello World\x00"
}

      

+2


source







All Articles