简介
将go代码生成为so库,可供c/c++调用,封装内部代码,实现代码隐蔽。
项目地址: https://github.com/acelj/tookit/tree/master/01goandc%2B%2B
目录
go代码
package main
import (
"C"
"fmt"
)
// 下面前面的空格不能有
//export Add
func Add(a, b int) int {
return a + b
}
//export Foo
func Foo(a string, b int) (int, int) {
fmt.Println("a = ", a)
fmt.Println("b = ", b)
c, d := 100, 200
return c, d
}
// go build -o test.so -buildmode=c-shared test.go
func main() {
fmt.Println("nihaoa")
fmt.Println(Add(1, 4))
}
C++代码
#include "test.h"
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <iostream>
GoString buildGoString(const char* p, size_t n)
{
return {p, static_cast<ptrdiff_t>(n)};
}
// 不需要重新定义Foo_return
// g++ main.cpp ./test.so
int main()
{
printf("demo...\n");
int re = Add(1,2);
printf("re = %d\n", re);
std::string str = "liudehua";
struct Foo_return res;
res = Foo(buildGoString(str.c_str(), str.size()), 111);
printf("re = %lld,%lld\n",res.r0, res.r1);
return 0;
}
上述比较示例比较简单,就不一一展开,如有需要请留言~~~