Golang 编译成 DLL 文件
本文内容纲要:
-Go调用
-Python调用
-C++调用
golang编译dll过程中需要用到gcc,所以先安装MinGW。
windows64位系统应下载MinGW的64位版本:https://sourceforge.net/projects/mingw-w64/
下载后运行mingw-w64-install.exe,完成MingGW的安装。
首先撰写golang程序exportgo.go:
packagemain
import"C"
import"fmt"
//exportPrintBye
funcPrintBye(){
fmt.Println("FromDLL:Bye!")
}
//exportSum
funcSum(aint,bint)int{
returna+b;
}
funcmain(){
//NeedamainfunctiontomakeCGOcompilepackageasCsharedlibrary
}
编译成DLL文件:
gobuild-buildmode=c-shared-oexportgo.dllexportgo.go
编译后得到exportgo.dll和exportgo.h两个文件。
参考exportgo.h文件中的函数定义,撰写C#文件importgo.cs:
usingSystem;
usingSystem.Runtime.InteropServices;
namespaceHelloWorld
{
classHello
{
[DllImport("exportgo.dll",EntryPoint="PrintBye")]
staticexternvoidPrintBye();
[DllImport("exportgo.dll",EntryPoint="Sum")]
staticexternintSum(inta,intb);
staticvoidMain()
{
Console.WriteLine("HelloWorld!");
PrintBye();
Console.WriteLine(Sum(33,22));
}
编译CS文件得到exe
cscimportgo.cs
将exe和dll放在同一目录下,运行。
>importgo.exe
HelloWorld!
FromDLL:Bye!
55
golang中的string参数在C#中可以如下引用:
publicstructGoString
{
publicstringValue{get;set;}
publicintLength{get;set;}
publicstaticimplicitoperatorGoString(strings)
{
returnnewGoString(){Value=s,Length=s.Length};
}
publicstaticimplicitoperatorstring(GoStrings)=>s.Value;
}
//func.go
packagemain
import"C"
import"fmt"
//exportAdd
funcAdd(aC.int,bC.int)C.int{
returna+b
}
//exportPrint
funcPrint(s*C.char){
/*
函数参数可以用string,但是用*C.char更通用一些。
由于string的数据结构,是可以被其它go程序调用的,
但其它语言(如python)就不行了
*/
print("Hello",C.GoString(s))//这里不能用fmt包,会报错,调了很久...
}
funcmain(){
}
编译
gobuild-ldflags"-s-w"-buildmode=c-shared-ofunc.dllfunc.go
还是有点大的,880KB,纯C编译的只有48KB,应该是没有包含全部的依赖吧,go是全包进来了
Go调用
packagemain
import(
"fmt"
"syscall"
)
funcmain(){
dll:=syscall.NewLazyDLL("func.dll")
add:=dll.NewProc("Add")
prt:=dll.NewProc("Print")
r,err,msg:=add.Call(32,44)
fmt.Println(r)
fmt.Println(err)
fmt.Println(msg)
name:=C.CString("Andy")
prt.Call(uintptr(unsafe.Pointer(name)))
}
out:
76
0
Theoperationcompletedsuccessfully.
HelloAndy
Python调用
fromctypesimportCDLL,c_char_p
dll=CDLL("func.dll")
dll.Add(32,33)
dll.Print(c_char_p(bytes("Andy","utf8")))
C++调用
#include<iostream>
#include<windows.h>
usingnamespacestd;
typedefint(*pAdd)(inta,intb);
typedefvoid(*pPrt)(char*s);
intmain(intargc,char*argv[])
{
HMODULEdll=LoadLibraryA("func.dll");
pAddadd=(pAdd)GetProcAddress(dll,"Add");
pPrtprt=(pPrt)GetProcAddress(dll,"Print");
cout<<add(321,33)<<endl;
prt("Andy");
FreeLibrary(dll);
return0;
}
本文内容总结:Go调用,Python调用,C++调用,
原文链接:https://www.cnblogs.com/dfsxh/p/10305072.html