在 C 中使用 GoString

由于 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;

}

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


问候语:


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


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


编辑 :


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


我 [...] 试图返回并仅打印一个 Go int(这是一个 C 的“long long”)并且也得到了错误的值。


所以看起来我的问题不在于字符串编码或空终止,而可能在于我如何编译整个事情


我很快就会添加我所有的编译步骤


qq_笑_17
浏览 400回答 2
2回答

慕丝7291255

printf期望以 NUL 结尾的字符串,但 Go 字符串不是以 NUL 结尾的,因此您的 C 程序表现出未定义的行为。请改为执行以下操作:#include "_obj/_cgo_export.h"#include <stdio.h>#include <stdlib.h>#include <string.h>int main() {&nbsp; &nbsp;GoString greeting = HelloWorld();&nbsp; &nbsp;char* cGreeting = malloc(greeting.n + 1);&nbsp; &nbsp;if (!cGreeting) { /* handle allocation failure */ }&nbsp; &nbsp;memcpy(cGreeting, greeting.p, greeting.n);&nbsp; &nbsp;cGreeting[greeting.n] = '\0';&nbsp; &nbsp;printf("Greeting message: %s\n", cGreeting);&nbsp; &nbsp;free(cGreeting);&nbsp; &nbsp;return 0;}或者:#include "_obj/_cgo_export.h"#include <stdio.h>int main() {&nbsp; &nbsp; GoString greeting = HelloWorld();&nbsp; &nbsp; printf("Greeting message: ");&nbsp; &nbsp; fwrite(greeting.p, 1, greeting.n, stdout);&nbsp; &nbsp; printf("\n");&nbsp; &nbsp; return 0;}或者,当然:func HelloWorld() string {&nbsp; &nbsp; return "Hello World\x00"}

尚方宝剑之说

这个评论很好地描述了我的问题:Call go functions from C你可以从 C 中调用 Go 代码,但目前你不能将 Go 运行时嵌入到 C 应用程序中,这是一个重要但微妙的区别。这就是我试图做的,这就是它惨遭失败的原因。我现在正在研究新-buildmode=c-shared选项
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go