unique_ptr和OpenSSL的STACK_OF(X509)*

unique_ptr and OpenSSL's STACK_OF(X509)*

本文关键字:X509 OF ptr OpenSSL unique STACK      更新时间:2023-10-16

我使用一些using语句和unique_ptr与OpenSSL一起工作,正如另一个问题所建议的那样。如果没有goto语句,代码会变得非常难看,我也不太喜欢goto语句。

到目前为止,我已经尽可能地改变了我的代码。以下是我使用的示例:
using BIO_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>;
using X509_ptr = std::unique_ptr<X509, decltype(&::X509_free)>;
using EVP_PKEY_ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
using PKCS7_ptr = std::unique_ptr<PKCS7, decltype(&::PKCS7_free)>;
...
BIO_ptr tbio(BIO_new_file(some_filename, "r"), ::BIO_free);

现在我需要一个STACK_OF(X509),我不知道,如果这也可能与unique_ptr。我正在寻找类似于下面的东西,但这是不工作。

using STACK_OF_X509_ptr = std::unique_ptr<STACK_OF(X509), decltype(&::sk_X509_free)>;

我还尝试了函子:

struct StackX509Deleter {
    void operator()(STACK_OF(X509) *ptr) {
        sk_X509_free(ptr);
    }
};
using STACK_OF_X509_ptr = std::unique_ptr<STACK_OF(X509), StackX509Deleter>;
STACK_OF_X509_ptr chain(loadIntermediate(cert.string()));

编译器接受此参数并运行应用程序。只有一个问题:在上面显示的其他unique_ptrs中,我总是指定了第二个参数,所以我敢打赌我遗漏了一些东西:

STACK_OF_X509_ptr chain(loadIntermediate(cert.string()),  ??????);

如何使用c++ unique_ptr和OpenSSL的STACK_OF(X509)* ?

我定义了一个正则函数:

void stackOfX509Deleter(STACK_OF(X509) *ptr) {
    sk_X509_free(ptr);
}

然后我在我的代码中使用它:

using STACK_OF_X509_ptr = std::unique_ptr<STACK_OF(X509),
    decltype(&stackOfX509Deleter)>;
STACK_OF_X509_ptr chain(loadIntermediate(cert.string()),
                    stackOfX509Deleter);