频道栏目
首页 > 资讯 > 其他 > 正文

如何把Golang编译成DLL文件

18-07-30        来源:[db:作者]  
收藏   我要投稿
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 两个文件。

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

using System;
using System.Runtime.InteropServices;
namespace HelloWorld
{
 class Hello 
 {
  [DllImport("exportgo.dll", EntryPoint="PrintBye")]
  static extern void PrintBye();

  [DllImport("exportgo.dll", EntryPoint="Sum")]
  static extern int Sum(int a, int b);

  static void Main() 
  {
Console.WriteLine("Hello World!");
PrintBye();

Console.WriteLine(Sum(33, 22));
  }
 }
}

编译 CS 文件得到 exe

csc importgo.cs

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

>importgo.exe

Hello World!
From DLL: Bye!
55

补充:

golang 中的 string 参数在 C# 中可以如下引用:


 public struct GoString
 {
  public string Value { get; set; }
  public int Length { get; set; }

  public static implicit operator GoString(string s)
  {
return new GoString() { Value = s, Length = s.Length };
  }

  public static implicit operator string(GoString s) => s.Value;
 }
相关TAG标签
上一篇:敏捷开发模型新秀SCRUM
下一篇:基于零控拦截流型最优控制的中制导律设计以及基于thaad的轨控发动机开关机规律设计
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站