c - 在 C 中使用 GoString

标签 c go cgo

感谢 cgo,我正在尝试在 C 程序中使用一些 Go 代码

我的 Go 文件如下所示:

package hello

import (
    "C"
)

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

我的 C 代码是这样的:

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

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

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

   return 0;
}

但是我得到的输出并不是我所期望的:

Greeting message: �

我猜这是一个编码问题,但关于它的文档很少,而且我对 C 几乎一无所知。

你知道那段代码出了什么问题吗?

编辑:

正如我刚才在下面的评论中所说:

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

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

我将很快添加所有编译步骤

最佳答案

printf 需要一个以 NUL 结尾的字符串,但 Go 字符串不是以 NUL 结尾的,所以你的 C 程序表现出未定义的行为。请改为执行以下操作:

#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;
}

或:

#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;
}

或者,当然:

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

关于c - 在 C 中使用 GoString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30917016/

相关文章:

c - 是的,我有这段代码,但系统命令不断出现错误

c - 将文件读入二维数组

go - 如何初始化 Go 结构中的特定字段

go - 在 Golang 项目中正确包含 C 库(按源代码)

gcc - 如何在cgo中使用Xlinker?格式错误的#cgo 参数 : -(

pointers - 从GO中的CGO转换字符串数组

c - 如何分配 UINT_MAX 的 block 大小?

c - MMX操作(加16bit没做)

去网/http请求

go - 如何将 os/exec 输出传递给 gin get