在测试使用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();
}
测试结果: