go语言生成DLL,供其他语言调用
一、go语言编写DLL(函数参数是字符串,输出是字符串或数值)
//file.go
package main
import "C"
//export ProcessString
func ProcessString(input *C.char) *C.char {
// 将输入参数转换为Go语言字符串
goInput := C.GoString(input)
output := "Hello, " + goInput
// 将输出字符串转换为C语言字符串
return C.CString(output)
}
//export ProcessStringLen
func ProcessStringLen(input *C.char) int {
// 将输入参数转换为Go语言字符串
goInput := C.GoString(input)
// 将输出字符串转换为C语言字符串
return len(goInput)
}
//export Sum
func Sum(a, b int) int {
return a + b
}
func main() {
// 这个 main 函数只是为了满足 Go 语言的要求,实际上不会被调用
}
二、编译成DLL
注意:需要 gcc 的支持,Windows 环境下的 gcc 系统是 MinGW
官网下载地址是 https://sourceforge.net/projects/mingw-w64/
可以写一个bat文件(生成x86):
set CGO_ENABLED=1
set CC=D:\setup\i686-w64-mingw32-gcc-4.7.4-release-win64_rubenvb\mingw32\bin\i686-w64-mingw32-gcc.exe
set CXX=D:\setup\i686-w64-mingw32-gcc-4.7.4-release-win64_rubenvb\mingw32\bin\i686-w64-mingw32-g++.exe
set GOOS=windows
set GOARCH=386
go build -buildmode=c-shared -o file.dll -tags stdc file.go
三、使用VS2019加载 file.dll
1、增加一个 class 文件:
class Class1
{
public const string DLL_NAME = "file.dll";
[DllImport(DLL_NAME, EntryPoint = "Sum", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
public static extern int Sum(int a, int b);
[DllImport(DLL_NAME, EntryPoint = "ProcessString", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
public static extern IntPtr ProcessString(byte[] msg);
[DllImport(DLL_NAME, EntryPoint = "ProcessStringLen", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
public static extern int ProcessStringLen(byte[] msg);
}
2、C#里面可以引用了:
byte[] bytes = System.Text.Encoding.UTF8.GetBytes( "中国abc123");
int num = Class1.ProcessStringLen(bytes);
//结果:num=12 (1个汉字3字节)
IntPtr output = Class1.ProcessString(bytes);
byte[] bytes3 = System.Text.Encoding.Unicode.GetBytes(Marshal.PtrToStringUni(output));//转成UNICODE编码
string dec = System.Text.Encoding.UTF8.GetString(bytes3);//再转成UTF8,防止乱码
//结果:dec = "中国abc123"
3、字符类型处理起来非常繁琐;只有数值类型都兼容
其中:
//struct goString
//{
// public string p;
// public int n;
//};
C#程序待研究处理
PB、VB6 里面可以直接引用数值参数;但是字符参数待交流补充
Delphi 10.4 测试:
引用函数:
{$R *.dfm}
Function ProcessString( a : PAnsiChar ) : PAnsiChar; stdcall; external 'file.dll';
调用:
Memo1.Lines.Add( ProcessString(PAnsiChar('test-abcd123学习')) );
//输出:Hello, test-abcd123学习