C#调用GO编写dll实例

在测试使用Go编写dll给C#进行调用的时候在传递字符串参数的,出现无法进行传递或是传递过程中丢失了数据。参考网上的结局方案字符串可以进行传递了但是中文又无法正常解析,由于Go中的编码使用的UTF编码,因此使用.Net的默认编码的时候Go就无法进行解析了,在Go中就出现了乱码。对此首先想到的解决方案是在C#中将字符串转换成UTF8的byte[]类型进行转换,故而可以将GoString的解决方案进行抛弃了。

以下是编写dll的go实例:

package main

import "C"
import (
	"fmt"
)

//export PrintHelloWorld
func PrintHelloWorld() {
	fmt.Println("Hello World!")
}

//export PrintMsg
func PrintMsg(msg *C.char) {
	// 输出参数
	var str string
	str = C.GoString(msg)
	fmt.Println(str)
}

//export Sum
func Sum(a, b int) int {
	return a + b
}

func main() {
	// bytes := []rune("124")
	// fmt.Println(string(bytes))
}

以下是C#中调用GO编写的dll

    class MyDll
    {
        public const string DLL_NAME = "MyDll.dll";

        [DllImport(DLL_NAME, EntryPoint = "PrintHelloWorld", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern void PrintHelloWorld();

        [DllImport(DLL_NAME, EntryPoint = "PrintMsg", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern void PrintMsg(byte[] msg);

        [DllImport(DLL_NAME, EntryPoint = "Sum", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern int Sum(int a,int b);

    }
 private static void Main(string[] args)
        {
            MyDll.PrintHelloWorld();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes("asfasdf中华人民共和国12323123");
            char[] chars = System.Text.Encoding.Default.GetChars(bytes);
            MyDll.PrintMsg(bytes);
            Console.WriteLine(MyDll.Sum(1,4));
            Console.ReadKey();
        }

测试结果:

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nicholasleo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值