Golang 编译成DLL文件的操作
作者:冷月醉雪 时间:2024-05-09 09:55:30
首先撰写golang程序exportgo.go:
package main
import "C"
import "fmt"
//export PrintBye
func PrintBye() {
fmt.Println("From DLL: Bye!")
}
//export Sum
func Sum(a int, b int) int {
return a + b;
}
func main() {
// Need a main function to make CGO compile package as C shared library
}
编译成 DLL 文件:
go build -buildmode=c-shared -o exportgo.dll exportgo.go
编译后得到 exportgo.dll 和 exportgo.h两个文件。
补充:Go1.10在编译成dll小实例
看代码吧~
package main
import (
"net"
)
//必须导入
import "C"
//编译成动态库也是必须的
func main() {}
//export Interfaces
func Interfaces(list []string, retlen *int) string {
interf, err := net.InterfaceAddrs()
if err != nil {
return err.Error()
}
for i, v := range interf {
if i >= len(list) {
break
}
list[i] = v.String()
}
*retlen = len(list)
return ""
}
编译命令:
go build -ldflags "-s -w" -buildmode=c-shared -o net.dll main.go
在当前文件夹会生成两个文件net.dll net.h
下面是使用:
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include "net.h"
int main()
{
GoString ret;
GoSlice slice;
slice.len=10;
slice.cap=0;
slice.data=calloc(10,sizeof(GoString));
GoInt retlen=0;
ret=Interfaces(slice,&retlen);
if (ret.n != 0)
{
char* retc = calloc(ret.n+1,sizeof(char));
memcpy(retc,ret.p,ret.n);
printf("Return value:%s\n", retc);
free(retc);
retc=NULL;
}
GoString* st=(GoString*)(slice.data);
for (int i=0;i<retlen;i++)
{
printf("%s\n", st[i].p);
}
free(slice.data);
slice.data=NULL;
return 0;
}
尽量不要用返回值来在C中处理,因为Go code不能在C分配的内存中存储指向Go分配的内存的指针,这个很重要,不然你就会在使用过程中各种崩溃。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持asp之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/lengyuezuixue/article/details/79360000
标签:Golang,编译,DLL
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
CTF中的PHP特性函数解析之上篇
2023-06-14 02:19:58
![](https://img.aspxhome.com/file/2023/8/55518_0s.jpg)
仿淘宝首页商品分类列表效果
2009-01-22 13:39:00
css网页下拉菜单制作方法(2):初步实现
2007-02-03 11:39:00
解决CentOS下ImportError: No module named '_sqlite3'的问题
2022-03-14 20:13:57
Golang中生成随机字符串并复制到粘贴板的方法
2024-02-16 08:32:10
SqlServer编写数据库表的操作方式(建库、建表、修改语句)
2024-01-15 11:38:57
sqlserver中查询横表变竖表的sql语句简析
2012-05-22 18:10:00
在Python安装MySQL支持模块的方法
2024-01-24 06:58:52
在Infopath中实现数据有效性验证的三种方法
2023-03-06 15:25:31
![](https://img.aspxhome.com/file/2023/0/132290_0s.png)
23个很棒的Python脚本集合分享(迷你项目)
2023-12-24 04:34:15
Design IT. (3),看不懂数据
2009-02-11 10:56:00
如何从数据库断开recordset,提高运行速度?
2009-11-15 20:01:00
数字格式化转换
2010-08-03 12:22:00
Python global全局变量函数详解
2023-02-02 07:00:17
javascript+css3开发打气球小游戏完整代码
2024-05-02 16:15:54
![](https://img.aspxhome.com/file/2023/1/132741_0s.gif)
在Linux系统的命令行中为MySQL创建用户的方法
2024-01-18 00:52:30
![](https://img.aspxhome.com/file/2023/3/71723_0s.jpg)
rs.open sql,conn,1,1全接触
2007-11-01 22:46:00
python中leastsq函数的使用方法
2023-11-11 06:03:28
![](https://img.aspxhome.com/file/2023/3/108153_0s.png)
Python实战之设计一个多功能办公小工具
2023-05-26 02:54:11
![](https://img.aspxhome.com/file/2023/2/109652_0s.png)
在SQL Server中使用SQL语句查询一个存储过程被其它所有的存储过程引用的存储过程名
2012-07-11 16:09:40