在Windows上开发桌面应用程序最快的方式无疑是使用C#,前有WinForm现有WPF,都是很好的开发框架,不管是MFC还是QT总还是复杂了一些。但是C#有一个最最大的缺点,就是没办法避免反编译,虽然我也经常反编译别人程序,但是绝不愿意看到自己的程序被别人反编译。
曾经我考虑过用C/C++做核心的功能,界面用C#做。虽然也是一种办法,但是C/C++还是麻烦了一些,而且在部署时,需要同时安装.NET Framework和VC Runtime,比较麻烦。
今天,我找到了一个很好的方法:核心功能用GO来做,界面用C#。GO的库相对较多,可以很方便的找到各种库,无论是http还是数据库的库。而且GO相对C/C++开发要快一些,无疑GO是比它们更合适的选择。
1. GO源码编译dll
// test.go
package main
// import "C" 不能少
import "C"
import "fmt"
// export声明导出函数名
//export Show
func Show() {
fmt.Println("hello dll")
}
//export Sum
func Sum(a int, b int) int {
return a + b;
}
func main(){
}
生成test.dll和test.h头文件:
go build -buildmode-c-shared -o test.dll test.go
虽然能生成,但是生成的dll还包含了一些import导入的函数,以后再想想如何只导出需要的函数。
2. 使用C#调用dll
c#调用c/c++的dll在已经很熟悉了,只写个例子:
// test.cs
using System;
using System.Runtime.InteropServices;
namespace HelloWorld
{
class hello
{
[DllImport("hello.dll", EntryPoint = "Show")]
static extern void Show();
[DllImport("hello.dll", EntryPoint = "Sum")]
static extern int Sum(int a, int b);
static void Main()
{
Show();
Console.WriteLine(Sum(1, 2));
}
}
}
使用命令行编译:
csc test.cs