- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
感谢 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/
感谢 cgo,我正在尝试在 C 程序中使用一些 Go 代码 我的 Go 文件如下所示: package hello import ( "C" ) //export HelloWorld fun
我使用 cgo 从 Go 调用 C 函数。该函数的返回类型为 uint8_u *。我知道它是一个字符串,需要在 Go 中打印它。 我在 myFile.go 中有以下内容 package main //
我是一名优秀的程序员,十分优秀!