为什么 libxml 不允许我创建具有 base64 文本内容的节点?

Why libxml won't allow me to create a node with base64 text content?

我正在使用 libxml2 创建一个 xml 文档,其中包含 C 中的 base64 编码文本。 但是,当我尝试添加一个包含 base64 编码的元素然后打印 xml 时,该元素为空。我还添加了printf来检查是否编码完成并打印出来。

这是我的程序:

xmlChar* createImportPKCS12Xml(char* userId, char* pkcs12, char* password, char* passwordForPkcs12) {
    xmlNodePtr personElem;
    xmlNodePtr userIdElem;
    xmlNodePtr pkcs12Elem;
    xmlNodePtr passwordElem;
    xmlNodePtr pkcs12PasswordElem;
    xmlDocPtr doc;
    xmlNodePtr root_node;
    xmlChar *xmlbuff;
    int buffersize;

    doc = xmlNewDoc(BAD_CAST "1.0");
    root_node = xmlNewNode(NULL, BAD_CAST "root");
    xmlDocSetRootElement(doc, root_node);
    root_node = xmlDocGetRootElement(doc);

    char* base = toBase64("abdsd");
    printf(base);

    personElem = xmlNewChild(root_node, NULL, BAD_CAST PERSON_ELEM, NULL);
    userIdElem = xmlNewChild(personElem, NULL, BAD_CAST USER_ID_ELEM, BAD_CAST userId);
    pkcs12Elem = xmlNewChild(root_node, NULL, BAD_CAST PKCS12_ELEM, BAD_CAST base);
    passwordElem = xmlNewChild(root_node, NULL, BAD_CAST PASSWORD_ELEM, BAD_CAST password);
    pkcs12PasswordElem = xmlNewChild(root_node, NULL, BAD_CAST PKCS12_PASSWORD_ELEM, BAD_CAST passwordForPkcs12);
    if ((personElem == NULL)
            || (userIdElem == NULL)
            || (passwordElem == NULL)
            || (pkcs12PasswordElem == NULL)
            || (pkcs12Elem == NULL)) {
        exit(EXIT_FAILURE);
    }
    xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1);

    xmlFreeDoc(doc);
    xmlCleanupParser();

    return xmlbuff;
} 

对于 base64 编码,我使用的是 openssl:

char* toBase64(char* str) {
    BIO *bio, *b64;
    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new_fp(stdout, BIO_NOCLOSE);
    BIO_push(b64, bio);
    BIO_write(b64, str, strlen(str));
    BIO_flush(b64);
    char* output = NULL;
    int sz = BIO_get_mem_data(b64, &output);
    BIO_free_all(b64);
    return output;
}

普通文本没有问题。有人有同样的问题并且可以提供帮助吗?或者有人可以建议使用 libxml2 执行此操作的不同方法吗?

编辑 1: 问题出在 toBase64 函数中。在我改变它之后一切正常:

char* toBase64(char* str) {
    BIO *bio, *b64;
    BUF_MEM *bufferPtr;

    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new(BIO_s_mem());
    bio = BIO_push(b64, bio);

    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); //Ignore newlines - write everything in one line
    BIO_write(bio, str, strlen(str));
    BIO_flush(bio);
    BIO_get_mem_ptr(bio, &bufferPtr);
    BIO_set_close(bio, BIO_NOCLOSE);
    BIO_free_all(bio);
        char* output;

    output=(*bufferPtr).data;
        return output;
}

编码函数的尾部看起来很吓人:

char* output = NULL;
int sz = BIO_get_mem_data(b64, &output);
BIO_free_all(b64);
return output;

你确定输出指针在BIO_free_all()之后有效吗?