Golang编译成DLL文件的方法

  介绍

这篇文章主要介绍了Golang编译成DLL文件的方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获、下面让小编带着大家一起了解一下。

Golang编译DLL过程中需要用到gcc,所以先安装MinGW。

windows 64位系统应下载MinGW的64位版本:https://sourceforge.net/projects/mingw-w64/

下载后运行mingw-w64-install。exe,完成MingGW的安装。

首先撰写golang程序exportgo。:

package 主要      import “C"   import “fmt"//export  PrintBye   func  PrintBye (), {   ,,,fmt.Println(“得到DLL:再见!“)   }//export 和   func 和(a , int, b  int), int  {   ,,,return  a  +, b;   }      func  main (), {   ,,,//,Need  a  main  function 用make  CGO  compile  package  as  C  shared 图书馆   }

编译成DLL文件:

go  build  -buildmode=c-shared  -o  exportgo.dll  exportgo。去

编译后得到exportgo。dll和exportgo。h两个文件。

参考exportgo。h文件中的函数定义,撰写c#文件importgo。cs:

using 系统;   using  System.Runtime.InteropServices;      namespace  HelloWorld   {   ,,,class  Hello    ,,,{   ,,,,,,,(DllImport (“exportgo.dll",,入口点=癙rintBye"))   ,,,,,,,static  extern  void  PrintBye ();      ,,,,,,,(DllImport (“exportgo.dll",,入口点=癝um"))   ,,,,,,,static  extern  int 和(int ,, int  b);      ,,,,,,,static  void 主要(),   ,,,,,,,{   ,,,,,,,,,,,Console.WriteLine (“Hello 世界!“);   ,,,,,,,,,,,PrintBye ();      ,,,,,,,,,,,Console.WriteLine (Sum(33岁,22));   ,,,,,,,}

编译CS文件得到exe

csc  importgo。cs

将exe和dll放在同一目录下,运行。

祝辞importgo.exe      Hello 世界!   得到DLL:再见!   55

golang中字符串的参数在c#中可以如下引用:

public  struct  GoString   ,,,{   ,,,,,,,public  string  Value {组,得到,,,}   ,,,,,,,public  int  Length {组,得到,,,}      ,,,,,,,public  static  implicit  operator  GoString (string  s)   ,,,,,,,{   ,,,,,,,,,,,return  new  GoString (), {, Value =,,, Length =, s.Length };   ,,,,,,,}      ,,,,,,,public  static  implicit  operator 字符串(GoString  s),=祝辞,s.Value;   ,,,} //,func.go   package 主要      import “C"   import “fmt"//export 添加   func 添加(a  C.int, b  C.int), C.int  {   return  a  + b   }//export 打印   func 打印(s  * C.char), {,,/*,   函数参数可以用,字符串,但是用* C.char更通用一些。   由于字符串的数据结构,是可以被其它去程序调用的,   但其它语言(如,python)就不行了   */打印(“Hello “, C.GoString (s)),//这里不能用fmt包,会报错,调了很久……   }   func  main (), {   }

编译

去构建-ldflags“- s -w"-buildmode=c-shared - o函数。dll函数。去
还是有点大的,880 kb,纯C编译的只有48 kb,应该是没有包含全部的依赖吧,去是全包进来了

去调用

package 主要   import  (   “fmt"   “syscall"   )      func  main (), {   dll :=, syscall.NewLazyDLL (“func.dll")   add :=, dll.NewProc (“Add")   prt :=, dll.NewProc(“保险单上)   呃,r,还以为;msg :=, add.Call(32岁,44)   fmt.Println(右)   fmt.Println (err)   fmt.Println(味精)      name :=, C.CString (“Andy")   prt.Call (uintptr (unsafe.Pointer(名称)))   }
:
  76
  0
  从而operation  completed 成功。
  Hello 安迪

Python调用

得到ctypes  import  CDLL, c_char_p   时间=dll  CDLL (“func.dll")   dll.Add(32岁,33)   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

Golang编译成DLL文件的方法