2 回答

TA貢獻1859條經驗 獲得超6個贊
printf期望以 NUL 結尾的字符串,但 Go 字符串不是以 NUL 結尾的,因此您的 C 程序表現(xiàn)出未定義的行為。請改為執(zhí)行以下操作:
#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"
}

TA貢獻1788條經驗 獲得超4個贊
這個評論很好地描述了我的問題:Call go functions from C
你可以從 C 中調用 Go 代碼,但目前你不能將 Go 運行時嵌入到 C 應用程序中,這是一個重要但微妙的區(qū)別。
這就是我試圖做的,這就是它慘遭失敗的原因。
我現(xiàn)在正在研究新-buildmode=c-shared
選項
- 2 回答
- 0 關注
- 419 瀏覽
添加回答
舉報