将go编译为dll

108 阅读1分钟

完整示例:

package main

import (
	"broadcastService/router"
	"broadcastService/service"
	"fmt"
	"net/http"
	"time"
)
import "C"

//export DStart
func DStart(port int) int { //dll调用
	go run(port)
	return 100
}

//export DInit
func DInit() int { //dll调用
	return 100
}

//export DStop
func DStop() int { //dll调用
	return 100
}

func main() {
	run(9000)
}

func run(port int) {
	service.InitConfig()

	defer service.File.Close() // 在程序结束时关闭日志文件
	if service.DB != nil {     // 程序结束前关闭数据库链接
		db, _ := service.DB.DB()
		defer db.Close()
	}
	r := router.Router()
	s := &http.Server{
		Addr:         fmt.Sprintf(":%d", port),
		Handler:      r,
		ReadTimeout:  100 * time.Second,
		WriteTimeout: 100 * time.Second,
	}
	s.ListenAndServe()
}

编译后dll对外提供三个函数(DStart、DInit、DStop)可被调用 使用gcc编译:go build -buildmode=c-shared -o broadcastService.dll main.go 编译后生成broadcastService.dll文件