Go语言第十八课 CGO

可借助CGO实现Go语言对C的调用,下面展示几种调用方式。

1、直接嵌套C代码

C代码内容如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* test_hello(const char* name){
    const char* hello=" -> hello";
    char* result=(char*)malloc(sizeof(char)*(strlen(name))+strlen(hello));
    strcpy(result,name);
    strcat(result,hello);
    return result;
}

int main()
{
    char* str=test_hello("yuyong");
    printf("%s\n",str);
    free(str);
}

运行结果:

yuyong -> hello

Go代码如下:

package main

/*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* test_hello(const char* name){
    const char* hello=" -> hello";
    char* result=(char*)malloc(sizeof(char)*(strlen(name))+strlen(hello));
    strcpy(result,name);
    strcat(result,hello);
    return result;
}
*/
import "C"
import "fmt"

func main() {
	fmt.Println(C.GoString(C.test_hello(C.CString("yuyong"))));
}

运行结果同C代码。

2、引用C源码方式

在Go main函数所在文件的同级目录下新建两个文件

test.h

#ifndef TEST_YUYONG_H
#define TEST_YUYONG_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* test_hello(const char* name);

#endif

test.c

#include"test.h"
char* test_hello(const char* name){
    const char* hello=" -> hello";
    char* result=(char*)malloc(sizeof(char)*(strlen(name))+strlen(hello));
    strcpy(result,name);
    strcat(result,hello);
    return result;
}

Go代码如下:

package main

/*
#include"test.c"
*/
import "C"
import "fmt"

func main() {
	fmt.Println(C.GoString(C.test_hello(C.CString("yuyong"))));
}

结果与1相同。

这两种方式调用C是最简单最基本的,下面我们尝试借助.so文件实现Go调用C/C++代码。

3、动态链接库方式

将上面的C文件(test.h和test.c)编译成动态链接库libtest.so

然后在Go main函数所在文件的同级目录下新建两个目录,lib和include

其中lib里面放入libtest.so,include里面放入test.h

Go代码如下:

package main

/*
#cgo CFLAGS : -I./include
#cgo LDFLAGS: -L./lib -ltest
#include "test.h"
*/
import "C"

import "fmt"

func main() {
	fmt.Println(C.GoString(C.test_hello(C.CString("yuyong"))));
}

配置环境变量

export LD_LIBRARY_PATH=/home/yong/Desktop/cgo-test20180723001/test_001/lib

其中LD_LIBRARY_PATH就是libtest.so所在目录

如果用的是Goland则可以配置如下:

Edit Configurations... --> Environment

添加,name=LD_LIBRARY_PATH,value=/home/yong/Desktop/cgo-test20180723001/test_001/lib

运行结果同上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值