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! 55golang中的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调用,Python调用,C++调用,
原文链接:https://www.cnblogs.com/dfsxh/p/10305072.html