在Go语言中迭代C数组结构

yjghlzjz  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(188)
package main

//#cgo LDFLAGS: -ldl -lp11
//#include <stdlib.h>
//#include <libp11.h>
import "C"

import (
        "log"
        "unsafe"
        "fmt"
        //"runtime"
        //"reflect"
)

func main(){
        var ctx *C.PKCS11_CTX
        ctx = C.PKCS11_CTX_new()
        //log.Println(ctx)

        cModulePath := C.CString("/home/procondutor/libaetpkss.so.3.0.3930")
        defer C.free(unsafe.Pointer(cModulePath))

        rc := C.PKCS11_CTX_load(ctx, cModulePath)
        if rc < 0 {
                log.Println("1 erro rc menor que 0")
                return
        }

        var slots, slot *C.PKCS11_SLOT
        var keys *C.PKCS11_KEY
        var nslots, nkeys uint
        p := unsafe.Pointer(&nslots)
        n := unsafe.Pointer(&nkeys)

        //log.Println(nkeys)
        rc = C.PKCS11_enumerate_slots(ctx, &slots, (*C.uint)(p))
        if rc < 0 {
                log.Println("2 erro rc menor que 0")
                return
        }

        slot = C.PKCS11_find_token(ctx, slots, C.uint(nslots));

        s := C.GoString(slot.manufacturer)
        fmt.Printf("%+v\n", s)

        cPin := C.CString("2903")
        defer C.free(unsafe.Pointer(cPin))

        rc = C.PKCS11_login(slot, 0, cPin);
        if rc < 0 {
                log.Println("3 erro rc menor que 0")
                return
        }

        rc = C.PKCS11_enumerate_keys(slot.token, &keys, (*C.uint)(n));
        if rc < 0 {
                log.Println("4 erro rc menor que 0")
                return
        }

我的问题出在PKCS11_enumerate_keys函数中,在C中,该函数根据下面的代码返回一个列表:

static void list_keys(const char *title, const PKCS11_KEY *keys,
        const unsigned int nkeys) {
    unsigned int i;

    printf("\n%s:\n", title);
    for (i = 0; i < nkeys; i++)
        printf(" * %s key: %s\n",
            keys[i].isPrivate ? "Private" : "Public", keys[i].label);
}

但是在Go语言中,它只返回第一个对象,如果我尝试在Go语言中迭代,我会得到如下错误:无效操作:无法索引索引键(类型为 *_Ctype_struct_PKCS11_key_st的变数)

slhcrj9b

slhcrj9b1#

我终于得到了它与代码如下:

list_keys := unsafe.Slice(keys, nkeys)
        for i := 0; i < int(nkeys); i++ {
                z:= C.GoString(slice[i].label)
                fmt.Println(z)
        }

相关问题