【问题标题】:How to store serialized element in PBC?如何在 PBC 中存储序列化元素?
【发布时间】:2018-08-15 03:51:26
【问题描述】:

我正在使用基于配对的加密库来实现应用程序。我想通过调用来存储元素

int element_length_in_bytes(element_t e)

int element_to_bytes(unsigned char *data, element_t e)

问题是值存储在unsigned char * 类型中。所以我不知道如何将它存储在文件中。

我尝试将其转换为 char * 并使用名为 jsoncpp 的库进行存储。但是,当我使用Json::Value((char *)data) 保留时,该值不正确。我该怎么做才能解决这个问题。

【问题讨论】:

    标签: c++ c serialization jsoncpp jpbc


    【解决方案1】:

    你需要先分配一些内存,然后把这个分配的内存的地址传递给 element_to_bytes() 函数,该函数会将元素存储在你分配的内存中。

    你怎么知道要分配多少字节?为此使用 element_length_in_bytes()。

    int num_bytes = element_length_in_bytes(e);
    /* Handle errors, ensure num_bytes > 0 */
    
    char *elem_bytes = malloc(num_bytes * sizeof(unsigned char));
    /* Handle malloc failure */
    
    int ret = element_to_bytes(elem_bytes, e);
    /* Handle errors by looking at 'ret'; read the PBC documentation */
    

    此时,您将元素呈现为位于 elem_bytes 中的字节。将其写入文件的最简单方法是使用 open()/write()/close()。如果出于某些特定原因必须使用 jsoncpp,则必须阅读 jsoncpp 的文档,了解如何编写字节数组。请注意,您调用的任何方法都必须询问正在写入的字节数。

    下面是使用 open()/write()/close() 的方法:

    int fd = open("myfile", ...)
    write(fd, elem_bytes, num_bytes);
    close(fd);
    

    完成后,你必须释放你分配的内存:

    free(elem_bytes);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      相关资源
      最近更新 更多