The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
nash

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

  •  
  •   nash · Oct 28, 2020 · 2620 views
    This topic created in 2057 days ago, the information mentioned may be changed or developed.
    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 replies    2020-11-04 11:43:14 +08:00
    MoYi123
        1
    MoYi123  
       Oct 28, 2020
    试了一下,
    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  
       Oct 28, 2020 via iPhone
    &data[0]
    jworg
        3
    jworg  
       Oct 28, 2020
    偏一下题,有这个调试的时间还不如直接 go 实现了,或者关键词 golang ccitt 就有相应的代码实现。另外提醒一下,cgo 其实调用是比较慢的,如果调用频繁的话,非常影响性能。
    rel
        4
    rel  
       Oct 29, 2020
    地址不对
    crc := C.crc_ccitt((*C.uchar)(unsafe.Pointer(&data[0])), C.int(len(data)))
    nash
        5
    nash  
    OP
       Nov 4, 2020
    反复试过了 楼上的是正确答案
    nash
        6
    nash  
    OP
       Nov 4, 2020
    谢谢大家
    nash
        7
    nash  
    OP
       Nov 4, 2020
    @jworg 恩 后期还是用 golang 去实现比较好,CGO 的交叉编译也是个坑
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   928 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 20:47 · PVG 04:47 · LAX 13:47 · JFK 16:47
    ♥ Do have faith in what you're doing.