當我運行此代碼時,我期望打印結果如A: 4, B: 89
。 但實際上,不顯示任何東西。不在cgo中顯示printf結果
爲什麼這個程序不顯示結果到標準輸出?
main.go:
package main
/*
#include "c.h"
*/
import "C"
import (
"unsafe"
)
type S struct {
A int
B int
}
func main() {
s := &S{A: 4, B: 89}
pass_to_c := (*C.S)(unsafe.Pointer(s))
C.gostruct(pass_to_c)
}
c.h
#include <stdio.h>
#include <stdlib.h>
typedef struct {
long int A;
long int B;
} S;
extern void gostruct(S *struct_s) {
printf("A: %ld, B: %ld\n", struct_s->A, struct_s->B);
}
轉到結構'S'和C結構'S'很可能不是您的系統上兼容。你不能把一個指針看作另一個指針。創建C結構類型的對象 - 您可以直接從Go創建和使用C結構。 – andlabs
在需要與C結構匹配的結構中使用特定大小的類型,如'int64'。在這種情況下,使用int64,或從C定義中獲取結構。由於您無法通過cgo訪問typedef結構,因此通常使用C封裝來訪問它們,而不是在Go中手動匹配結構。這樣你可以讓cgo自動生成它們,而不是手動檢查大小和對齊方式。 – JimB