• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#调用Go版DLL

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go从入门到精通——编写您的第一个GO程序——Hello World!发布时间:2022-07-10
下一篇:
go文件操作打开和读取发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap