gpt4 book ai didi

c - 在 C 中使用 GoString

转载 作者:IT王子 更新时间:2023-10-29 01:10:41 25 4
gpt4 key购买 nike

感谢 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com