go 调用C语言函数或者库

1.查看cgo是否开启

复制代码
go env  | grep CGO_ENABLED
CGO_ENABLED='1'
  1. go程序中加入 import "C"

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

单行注释使用//

多行注释使用/* */

  1. 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语言的数据类型对应表

  1. 直接在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

相关推荐
微学AI7 小时前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
豆瓣鸡8 小时前
算法日记 - Day3
java·开发语言·算法
mldong8 小时前
从 mldong 到 jeeflow:一个工作流引擎的独立进化
后端
Achou.Wang8 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
韭菜炒鸡肝天8 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
陈随易9 小时前
MoonBit抓包模块pcap,查看电脑的每一次联网通信
前端·后端·程序员
Aaron - Wistron9 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
卷无止境9 小时前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境9 小时前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
Dxy123931021610 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python