unique_ptr 和 OpenSSL 的 STACK_OF(X509)*

unique_ptr and OpenSSL's STACK_OF(X509)*

我使用一些 using 语句和 unique_ptr 来使用 OpenSSL,如 。否则,代码会变得非常丑陋,而且我不太喜欢 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)>;

我也试过 Functor:

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);