C#调用Go版DLL

private void button6_Click(object sender, EventArgs e)
{
    byte[] inParam = null;
    IntPtr ptr = IntPtr.Zero;
    int outlen = -1;
    string outstr = "";

    inParam = Encoding.UTF8.GetBytes("执着不可取");

    int ret = Inwhtl_DLL.TestApi(inParam,ref ptr, ref outlen);

    if(outlen > 0)
    {
        outstr = Marshal.PtrToStringAnsi(ptr, (int)outlen);
        byte[] byt = strToToHexByte(outstr);
        outstr = Encoding.UTF8.GetString(byt);

        MessageBox.Show(outstr);

    }
}

/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private static byte[] strToToHexByte(string hexString)
{
    hexString = hexString.Replace(" ", "");
    if ((hexString.Length % 2) != 0)
        hexString += " ";
    byte[] returnBytes = new byte[hexString.Length / 2];
    for (int i = 0; i < returnBytes.Length; i++)
        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
    return returnBytes;
}


package main

import "C"
import (
    "e.coding.net/jiftle/inwarehousetool/checktool/chktl"
    "encoding/hex"
    "fmt"
    "os"
)

//export Sum
func Sum(a int, b int) int {
    //最简单的计算和
    return a + b
}

//export TestApi
func TestApi(inParam *C.char, outParam **C.char, outlen *C.int) int {
    // 输入参数
    in := C.GoString(inParam)

    // 注意事项
    s := "1122ABC你" + in

    bytS := []byte(s)
    s = hex.EncodeToString(bytS)

    // 输出参数
    *outParam = C.CString(s)
    var noutlen int
    noutlen = len(C.GoString(*outParam))
    *outlen = C.int(noutlen)

    return 0
}



[DllImport("dlltest.dll", CharSet = CharSet.Ansi)]
public static extern int TestApi(byte[] inParam,ref IntPtr outstr, ref int outlen);

 

注意事项:

    很多文章上,使用GoString结构体和Go导出文件.h中对应,经过多次测试,发现程序极易崩溃。

原因可能有以下几个方面:

1. 结构体的内存映射问题,字段顺序需要严格对应,字段内存占用长度

2. 返回go string类型,内部不能使用 + 拼接,外部传入的string参数,否则立即崩溃,无任何提示

结论:

1. 建议使用*C.char作为入参,**C.char作为出参,*C.int提供出参内存占用长度

2. 中文乱码,go内部采用UTF8编码,每个中文字符占用3个字节,string默认采用Unicode每个字符4个字节。 传参之前先做转换(字符串转十六进制字符串字符串,互转)

 

 

https://www.cnblogs.com/Leo_wl/p/12075987.html

 

posted @ 2020-05-02 10:55  jiftle  阅读(2182)  评论(0编辑  收藏  举报