cgo

本文详细介绍了Go语言与C语言交互的关键要点,包括C字符串管理、C类型直接访问、C类型大小获取、C函数调用错误处理,以及Go函数如何在C代码中使用。同时,强调了Go指针在C内存中的存储规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Go references to C
1、Memory allocations made by C code are not known to Go's memory manager. When you create a C string with C.CString (or any C memory allocation) you must remember to free the memory when you're done with it by calling C.free.

2 、To access a struct, union, or enum type directly, prefix it with struct_, union_, or enum_, as in C.struct_stat.

3、The size of any C type T is available as C.sizeof_T, as in C.sizeof_struct_stat.

4、_, err := C.voidFunc()  C errno variable as an error (use _ to skip the result value if the function returns void).

C references to Go 
1、go函数导出,单个返回值与多返回值。found in the _cgo_export.h generated header, after any preambles copied from the cgo input files. Functions with multiple return values are mapped to functions returning a struct.
//export MyFunctionf
func MyFunction(arg1, arg2 int, arg3 string) int64 {...}

 


//export MyFunction2f
func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}
they will be available in the C code as:
extern int64 MyFunction(int arg1, int arg2, GoString arg3);

extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);

2 、Go code may not store a Go pointer in C memory. C code may store Go pointers in C memory, subject to the rule above: it must stop storing the Go pointer when the C function returns.

  

转载于:https://www.cnblogs.com/xiaomayi-cyj/p/10348279.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值