go语言生成DLL,供其他语言调用

本文介绍了如何使用Go语言编写DLL,并提供编译和在C#、Delphi等语言中调用的示例,展示了字符串和数值参数的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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学习
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值