duanjieyi6582 2018-08-20 06:26
浏览 164
已采纳

将字符串传递给Syscall(uintptr)

I need to pass string as param to C DLL in golang, i want to get something like this:

  proc, e = syscall.GetProcAddress(h, "JLINKARM_ExecCommand") //One of the functions

    vals := []string{"device = STM32F429ZI"}
    start := uintptr(unsafe.Pointer(&vals[0]))

    asd, _, _ = syscall.Syscall6(uintptr(proc), 3, start, 0, 0, 0, 0, 0) 

but it doesn't work. Syscall take as param uintptr. I can't use C package because it won't build on windows.

In C it works like:

strcpy(acIn, "device = STM32F407IE");

JLINKARM_ExecCommand(acIn, &acOut[0], sizeof(acOut));

So it is any chance that C DLL can get string param and use it properly?

  • 写回答

1条回答 默认 最新

  • doudao2407 2018-08-20 07:04
    关注

    To pass a string to syscall you need to pass a pointer to the first character of the string. The first question is what string encoding your DLL function expects. Go strings are encoded as UTF-8 unicode so if your C function expects something else you have to convert them first. Here are some common cases:

    1) ASCII string

    Say your C function expects a zero-terminated ASCII string, then you can do the following:

    s := "some string"
    b := append([]byte(s), 0)
    syscall.Syscall(uintptr(proc), 1, uintptr(unsafe.Pointer(&b[0])), 0, 0)
    

    First convert your string to a byte array and add the zero that C expects at the end. Then pass the pointer to the first byte character.

    To be safe you should also make sure that you actually pass in only valid ASCII strings and no invalid characters. Usually only characters in the range [0..127] are valid for general ASCII. The rest depends on the current codepage.

    2) UTF-16 on Windows

    If you call into a Windows DLL you want to usually use their UTF-16 version of that function, e.g. SendMessageW, and thus need to convert your string to UTF-16. Luckily there is a wrapper function for that under Windows, so you can just do the following:

    s := "some string"
    s16, err := syscall.UTF16PtrFromString(s)
    if err == nil {
        syscall.Syscall(uintptr(proc), 1, uintptr(unsafe.Pointer(s16)), 0, 0)
    }
    

    This will convert to UTF-16 and append the expected zero at the end for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP