CGO输出helloworld

发布时间 2023-07-19 22:36:14作者: 念秋

使用CGO输出helloworld

本人windows版本

go version go1.18.3 windows/amd64
 dir   目录: D:\cgo\main


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         2023/7/19     21:59                .idea
-a----         2023/7/19     22:18           1960 first.go
-a----         2023/7/19     22:03             72 hello.c
-a----         2023/7/19     22:03            101 hello.cpp
-a----         2023/7/19     22:07            204 hello.go
-a----         2023/7/19     22:10            284 hello.h
-a----         2023/7/19     22:11        6008785 main.exe

first.go

package main
//简单的说,把下面注释的内容写在注释里面显然是比较麻烦的。所有简便起见,把注释的内容写在hello.h里面,然后只引入一个hello.h就好了。
/*
#include<hello.h>
//#include<stdio.h>
//有没有static并不影响,也不需要大小写
//static void sayHello(const char* s) {
//	puts(s);
//}
//write by c
//void sayHelloByC(const char* s);
//write by c++
//void sayHelloByCpp(const char* s);
//void sayHelloByGo(char* s);
*/
import "C"
import "fmt"

func main() {
	//println("hello world")
	C.puts(C.CString("print hello by c.puts\n"))
	C.sayHello(C.CString("this is hello\n"))                   //直接写一个static函数
	C.sayHelloByC(C.CString("this is hello from c file\n"))    //在这里定义函数,用C实现
	C.sayHelloByCpp(C.CString("this is hello from c++ file"))  //在这里定义函数,用C++实现
	C.sayHelloUseGo(C.CString("this is hello from go file\n")) //一个头文件,用go语言实现功能
	C.sayHelloByGo(C.CString("this is hello from go file too\n"))
	sayHelloUseGo(C.CString("just call from go\n"))
	sayHelloByGo(C.CString("just call from go too"))
}

hello.h

void sayHelloUseGo(char* s);
#include<stdio.h>
//有没有static并不影响,也不需要大小写
static void sayHello(const char* s) {
	puts(s);
}
//write by c
void sayHelloByC(const char* s);
//write by c++
void sayHelloByCpp(const char* s);

void sayHelloByGo(char* s);

hello.go

package main

import "C"
import "fmt"

//export sayHelloUseGo
func sayHelloUseGo(s *C.char) {
	fmt.Print(C.GoString(s))
}

//export sayHelloByGo
func sayHelloByGo(s *C.char) {
	fmt.Print(C.GoString(s))
}

hello.c

#include <stdio.h>

void sayHelloByC(const char* s) {
    puts(s);
}

hello.cpp

#include<iostream>
extern "C" void sayHelloByCpp(const char* s) {
    std::cout<<s<<std::endl;
}

go run .
或者
go build

执行结果

print hello by c.puts

this is hello

this is hello from c file

this is hello from c++ file
this is hello from go file
this is hello from go file too
just call from go
just call from go too

编程语言之间的相互调用显然是非常方便的,不用再重复开发,这里只是简单举例使用cgo进行输出字符串,至于其他的数据类型,也是大差不差的。