c++ - unique_ptr 和 OpenSSL 的 STACK_OF(X509)*

标签 c++ c++11 openssl smart-pointers unique-ptr

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

关于c++ - unique_ptr 和 OpenSSL 的 STACK_OF(X509)*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38145761/

相关文章:

c++ - 使用 size() 返回当前在我的类中的元素数 (c++)

c - 使用 openssl 进行 Base64 解码的一个非常奇怪的错误

c++ - 使用 OpenSSL API 准备 secret 文件以解密 Wireshark 中的 TLS 1.3 流量

c++ - 将 vector 与对象一起使用错误

c++ - QPixmap加载段错误

c++ - 不同的智能指针可以引用同一个对象吗?

c++ - std::unordered_map 指针/引用失效

linux - gcc .h 没有这样的文件或目录(openssl、anaconda、Ubuntu 18.04

c++ - 函数不返回应该返回的内容 - C++

c++ - MSVC 错误 - 错误 C2373 : 'description' : redefinition; different type modifiers