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

相关推荐
007php00718 分钟前
服务器上PHP环境安装与更新版本和扩展(安装PHP、Nginx、Redis、Swoole和OPcache)
运维·服务器·后端·nginx·golang·测试用例·php
艾莉丝努力练剑2 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
武子康3 小时前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
椰椰椰耶5 小时前
【Spring】拦截器详解
java·后端·spring
brzhang6 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
倔强青铜36 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian7 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼7 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上7 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt