其他分享
首页 > 其他分享> > go和c混编

go和c混编

作者:互联网

c主程序中调用go语言函数
go语言函数调用c语言函数

代码目录:
	[root@localhost test1]# tree 
	.
	├── a.out
	├── foo.c
	├── foo.h
	├── libtest.h
	├── libtest.so
	├── main.c
	├── main.go
	└── num.c

编译:
	mv main.c ../
	go build -o libtest.so -buildmode=c-shared 
	mv ../main.c .
	gcc main.c foo.c num.c -L. -ltest

测试:
	[root@localhost test1]# ./a.out 
	c main a_local[100]
	c main a_bygo[100]
	c main a_local[50]
	c main a_bygo[50]

FAQ:
1:go语言函数需要编译成库的形式给c语言进行调用,如示例中使用-buildmode=c-shared进行编译,go中需要对接口进行export 
2:通过// #include "foo.h" import "C",C.init(ptr)类似的方式在go中调用c语言封装的函数
#include <stdio.h>


#include "libtest.h"

extern int a;

int main()
{
        printf("c main a_local[%d]\n", a);
        go_init(&a);
        printf("c main a_bygo[%d]\n", go_geta());
        go_seta(50);
        printf("c main a_local[%d]\n", a);
        printf("c main a_bygo[%d]\n", go_geta());
}
int geta();
int seta(int);
int init(int *);
static int *a;


int geta() {
        return *a;
}

int seta(int v) {
        *a = v;
}

int init(int * ptr) {
        a = ptr;
}
int a= 100;
package main

// #include "foo.h"
import "C"



//export go_geta
func go_geta() C.int {
        return C.geta()
}

//export go_seta
func go_seta(v C.int) {
        C.seta(v)
}

//export go_init 
func go_init(ptr *C.int) {
        C.init(ptr)
}

func main() {
}

标签:foo,int,geta,混编,init,go,main
来源: https://blog.csdn.net/javaxflinux/article/details/98489700