1. 编译golang 静态库
package main import ( "C" "fmt" ) //export Foo func Foo(a, b int) int { return a + b } //export Bar func Bar() { fmt.Println("Hello, I'm LiLei.") } func main() { }
使用命令编译得到静态库和头文件
go build -o main.a -buildmode=c-archive main.go
2. 编写C的动态库
demo.h
int foo();
int bar();
demo.c
#include "demo.h"
#include <stdio.h>
int foo(){
int a[3] = {1,2,3};
int s = 0;
int len = sizeof(a)/sizeof(a[0]);
printf("len=%d\n", len);
for(int i=0; i<len;i++){
s+=a[i];
}
printf("calc s=%d\n", s);
return s;
}
int bar(){
printf("hello, I am Lilei");
return 32;
}
gcc -shared -fpic -o demo.so demo.c
会生成demo.so动态库文件
3. C 入口程序编译
test.c
#include "demo.h"
#include "main.h"
#include <stdio.h>
int main(){
foo();
bar();
Bar();
GoInt32 a=3;
GoInt32 b=4;
GoInt s = Foo(a,b);
printf("s=%d\n", s);
return 0;
}
将GOlang 静态库文件和头文件复制到C文件夹下
执行GCC 命令
>gcc -v test.c -o test1 main.a demo.so -lWinMM -lntdll -lWS2_32
运行test1