gpt4 book ai didi

c - 如何从 C 库中检索 probuf

转载 作者:数据小太阳 更新时间:2023-10-29 03:18:28 25 4
gpt4 key购买 nike

我正在尝试使用 Google Protocol Buffers 与 Go 中的 C 库进行通信,但我无法使其正常工作。我在尝试将 protobuf 发送到 C 库时遇到错误

我将发布最少的代码来重现我现在面临的错误(我删除了大部分 C 部分,因为它与此错误无关):

    /*
#cgo CFLAGS: -I@CURRENT_SOURCE_DIR@/../../library/crnd/include -
I@CMAKE_CURRENT_BINARY_DIR@/../../library
#cgo LDFLAGS: -L@CRND_LIBRARY_PATH@ -lcrnd

#include <api_c.h>
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>

typedef struct SerializedStruct {
void* data;
int64_t size;
} Serialized;
*/
import "C"

func (crnd wrapper) MyFunction() {

// Create a protobuf
sample_request := &messages.SampleRequest { ... add members ...}
fmt.Printf(proto.MarshalTextString(sample_request)); // print the message to check it works

data, err := proto.Marshal(sample_request)
if err != nil {
log.Fatal("marshaling error: ", err)
}

sample_request_serialized := C.Serialized {
data: pointer.Save(data),
size: C.int64_t(len(data)),
}

// Here I would send my protobuf to the C library, but it is not
// working, so I'm trying to reconstruct the protobuf to check
// if something is broken before getting to the C side

// Let's reconstruct the protobuf back
data_req := (*[1 << 30]byte)(sample_request_serialized.data)[:int(sample_request_serialized.size):int(sample_request_serialized.size)]
sample_req := &messages.SampleRequest{}
err := proto.Unmarshal(data_req, sample_req)
if err != nil {
log.Fatal("unmarshaling error: ", err)
}
}

我收到以下错误:

unmarshaling error: proto: crnd.SampleRequest: illegal tag 0 (wire type 0)

最佳答案

我设法让它可以创建缓冲区的副本(取自 this question ):

    ...

p := C.malloc(C.size_t(len(data)))
defer C.free(p)
cBuf := (*[1 << 30]byte)(p)
copy(cBuf[:], data)

sample_request_serialized := &C.Serialized {
data: p,
size: C.int64_t(len(data)),
}

关于c - 如何从 C 库中检索 probuf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57515234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com