当前位置: 首页> 游戏> 评测 > go 调用C语言函数或者库

go 调用C语言函数或者库

时间:2025/7/12 10:40:06来源:https://blog.csdn.net/du2005023029/article/details/141196169 浏览次数:1次

1.查看cgo是否开启

go env  | grep CGO_ENABLED
CGO_ENABLED='1'

2. go程序中加入 import "C" 

通过 import “C” 语句启用 CGO 特性后,CGO 会将上一行代码所处注释块的内容视为 C 代码块

单行注释使用//
多行注释使用/*   */

3. go 与C 类型转换

在go安装目录 src\cmd\cgo 中定义

func C.CString(string) *C.char
func C.CBytes([]byte) unsafe.Pointer
func C.GoString(*C.char) string
func C.GoStringN(*C.char, C.int) string
func C.GoBytes(unsafe.Pointer, C.int) []byte

GO语言与C语言的数据类型对应表

3. 直接在go文件中使用函数

package main/*
#include <stdio.h>
int printHello(const char *str){printf("%s\n",str);return 3;
}
*/
import "C"
import ("fmt"
)func main() {fmt.Println("Hello World!")fmt.Println(C.printHello(C.CString("nihao")))
}

4.使用动态库

myprint.c

#include "myprint.h"
#include <stdio.h>
int printHello(const char *str){printf("%s\n",str);return 3;
}

myprint.h

#ifndef __MYPRINTF_H
int printHello(const char *str);
#endif

编译动态库

gcc -fPIC -shared -o libmyprint.so myprint.c

将编译后的动态库拷贝至系统lib路径 ,或者自定义路径下 然后修改/etc/ld.so.conf

执行ldconfig

使用动态库序号包含3行

#cgo CFLAGS: -ImyLibIncPath
#cgo LDFLAGS:  -LmyLibIncPath -lmyprint
#include "myprint.h"

package main/*
#cgo CFLAGS: -I./
#cgo LDFLAGS: -L./ -lmyprint
#include "myprint.h"
*/
import "C"
import ("fmt"
)func main() {fmt.Println("Hello World!")fmt.Println(C.printHello(C.CString("nihao")))
}

5.go与c数据转换可以参考

https://www.cnblogs.com/zhaoyingjie/p/15683384.html

关键字:go 调用C语言函数或者库

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: