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

相关推荐
东风破_5 小时前
danci 2:创建的单词书到底存在哪里?从 Supabase 一路理解 ORM、Drizzle 和 RLS
数据库·后端·node.js
CoderIsArt5 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
东风破_5 小时前
danci 项目(三):从 JSON 数据到 AI Coding,真实项目里的数据清洗、Prompt 和工程规范
前端·后端·node.js
东风破_6 小时前
danci 项目(一):从需求到架构,一个单词学习系统为什么会这样设计
前端·后端·node.js
jay神7 小时前
【计算机毕业设计】基于SpringBoot的程序教学辅助系统
java·前端·vue.js·spring boot·后端·毕业设计·课程设计
AI情绪识别开源7 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
「QT(C++)开发工程师」8 小时前
C++ auto 用法详解
开发语言·c++
OPEN-F9 小时前
C++STL教程:容器适配器与实用工具
开发语言·c++
yaoxin5211239 小时前
507. Java 反射 - 在 BeanFactory 中实现依赖注入
java·开发语言