英文:
Does not display printf result in cgo
问题
当我运行这段代码时,我期望输出结果为A: 4, B: 89
。但实际上,没有显示任何内容。
为什么这个程序没有将结果显示到标准输出(stdout)?
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);
}
英文:
When I ran this code, I expected to printing result like A: 4, B: 89
.
But actually, Does not display nothing.
Why this program does not display result to stdout?
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);
}
答案1
得分: 2
感谢您的评论。
我可以通过以下代码获得预期的结果
main.go:
package main
/*
#include "c.h"
*/
import "C"
import (
"unsafe"
)
type S struct {
A int64 // 64位整数
B int64 // 64位整数
}
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 long int A; // 64位整数
long long int B; // 64位整数
} S;
extern void gostruct(S *struct_s) {
printf("{A: %lld, B: %lld}\n", struct_s->A, struct_s->B);
}
我认为结构体字段在不同语言之间必须使用相同的类型。
在问题的代码中,结构体字段的类型不同。
(C语言结构体:32位整数,Go语言结构体:64位整数)
在答案的代码中,结构体字段在两种语言之间是相同的。
(两个结构体都是64位整数)
请注意,我的架构是darwin/amd64
英文:
Thanks for comments.
I can got expected result with below codes
main.go:
package main
/*
#include "c.h"
*/
import "C"
import (
"unsafe"
)
type S struct {
A int64 // 64bit int
B int64 // 64bit 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 long int A; // 64bit int
long long int B; // 64bit int
} S;
extern void gostruct(S *struct_s) {
printf("{A: %lld, B: %lld}\n", struct_s->A, struct_s->B);
}
I suppose struct field must use same type between languages.
In question code, struct fields type are not same.
(C struct: 32bit int, Go struct: 64bit int)
In answer code, struct field is same between language.
(both struct: 64bit int)
Note that My architecture is darwin/amd64
答案2
得分: 1
我在LiteIDE中运行程序时,没有显示C printf的输出。
但是在终端中运行相同的程序,
然后C printf的输出会显示出来。
英文:
I run program in LiteIDE, not show c printf output.
But run the same program in terminal,
then c printf output displayed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论