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

相关推荐
程序员-珍12 分钟前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
弱冠少年19 分钟前
websockets库使用(基于Python)
开发语言·python·numpy
长天一色20 分钟前
C语言日志类库 zlog 使用指南(第五章 配置文件)
c语言·开发语言
liuxin3344556629 分钟前
教育技术革新:SpringBoot在线教育系统开发
数据库·spring boot·后端
一般清意味……32 分钟前
快速上手C语言【上】(非常详细!!!)
c语言·开发语言
卑微求AC33 分钟前
(C语言贪吃蛇)16.贪吃蛇食物位置随机(完结撒花)
linux·c语言·开发语言·嵌入式·c语言贪吃蛇
技术无疆42 分钟前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
金灰1 小时前
HTML5--裸体回顾
java·开发语言·前端·javascript·html·html5
爱上语文1 小时前
Java LeetCode每日一题
java·开发语言·leetcode
bug菌1 小时前
Java GUI编程进阶:多线程与并发处理的实战指南
java·后端·java ee