V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
nash
V2EX  ›  Go 编程语言

问大家一下 CGO 里面的参数要怎么传?

  •  
  •   nash · 2020-10-28 11:15:45 +08:00 · 1751 次点击
    这是一个创建于 1248 天前的主题,其中的信息可能已经有所发展或是发生改变。
    package main
    
    /*
    #include <stdio.h>
    unsigned short crc_ccitt(unsigned char *q, int len) {
    	int i, j;
    	int c, crc = 0xffff;
    	for(i=0; i<len; i++) {
    		c = q[i] & 0x00ff; crc ^= c;
    		for(j=0; j<8; j++) {
    			if((crc&0x0001) != 0) {
    			crc >>= 1;
    			crc ^= 0xA001;
    			} else {
    				crc >>= 1;
    			}
    		}
    	}
    	return (unsigned short)crc;
    }
    */
    import "C"
    import (
    	"fmt"
    	"unsafe"
    )
    
    func Crc() {
    	data := []byte{0x99, 0x88, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x0e, 0x0c, 0x32, 0x31, 0x30, 0x31, 0x31, 0x38, 0x30, 0x37, 0x30, 0x30, 0x31, 0x30, 0x18}
    	crc := C.crc_ccitt((*C.uchar)(unsafe.Pointer(&data)), C.int(len(data)))
    	// 期望结果 56 f9
    	fmt.Printf("%X", crc)
    }
    
    func main() {
    	Crc()
    }
    

    有个 CRC 校验的东西是 C 写的,我就想着难得去用 go 实现直接 CGO 调用,发现这个参数怎么传都不对,请教下各位大神,谢谢

    7 条回复    2020-11-04 11:43:14 +08:00
    MoYi123
        1
    MoYi123  
       2020-10-28 12:03:07 +08:00
    试了一下,
    data := [26]byte{
    0x99, 0x88, 0x02, 0x00, 0x00,
    0x01, 0x00, 0x00, 0x00, 0x0a,
    0x00, 0x0e, 0x0c, 0x32, 0x31,
    0x30, 0x31, 0x31, 0x38, 0x30,
    0x37, 0x30, 0x30, 0x31, 0x30,
    0x18}
    这样能返回 F9 56
    imgk
        2
    imgk  
       2020-10-28 12:20:54 +08:00 via iPhone
    &data[0]
    jworg
        3
    jworg  
       2020-10-28 12:48:59 +08:00
    偏一下题,有这个调试的时间还不如直接 go 实现了,或者关键词 golang ccitt 就有相应的代码实现。另外提醒一下,cgo 其实调用是比较慢的,如果调用频繁的话,非常影响性能。
    rel
        4
    rel  
       2020-10-29 14:40:35 +08:00
    地址不对
    crc := C.crc_ccitt((*C.uchar)(unsafe.Pointer(&data[0])), C.int(len(data)))
    nash
        5
    nash  
    OP
       2020-11-04 11:40:50 +08:00
    反复试过了 楼上的是正确答案
    nash
        6
    nash  
    OP
       2020-11-04 11:41:24 +08:00
    谢谢大家
    nash
        7
    nash  
    OP
       2020-11-04 11:43:14 +08:00
    @jworg 恩 后期还是用 golang 去实现比较好,CGO 的交叉编译也是个坑
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5290 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 08:15 · PVG 16:15 · LAX 01:15 · JFK 04:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.