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

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)保留时,该值不正确。我应该怎么做才能解决这个问题。

最佳答案

您需要先分配一些内存,然后将该分配的内存的地址传递给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);

09-04 07:06
查看更多