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

b9b01e071c78aa450f3f303f5f72992b.png

2. 编写C的动态库

demo.h

int foo();

int bar();

demo.c

#include "demo.h"

#include

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

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

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文件夹下

e1d4a26b7fa842d1d03bdfed929aa9e9.png

执行GCC 命令

>gcc -v test.c -o test1 main.a demo.so -lWinMM -lntdll -lWS2_32

运行test1

7955775a64b043b043e5153e559e549d.png

有疑问加站长微信联系(非本文作者)