本文介绍了unique_ptr和OpenSSL的STACK_OF(X509)*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用使用语句和 unique_ptr 来使用OpenSSL,因为。没有,代码变得真的丑陋,我不是一个喜欢goto语句。

I use some using statements and unique_ptr to work with OpenSSL, as suggested in another question. Without, code becomes really ugly and I am not so much a fan of goto statements.

到目前为止我已经改变了我的代码尽可能。下面是例子,我使用:

So far I have changed my code as far as possible. Here are examples, what I use:

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 。我正在寻找类似下面的东西,但是这不工作。

Now I have the need of a STACK_OF(X509) and I do not know, if this is also possible with unique_ptr. I am looking for something similar to below, but this is not working.

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

我也尝试过Functor:

I also tried the 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 如上所示,我总是指定了第二个参数,所以我打赌,我错过了一些:

The compiler accepts this and the application runs. Just one question: In other unique_ptrs as shown above, I always had specified a second argument, so I bet I am missing something:

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

如何使用C ++ unique_ptr 和OpenSSL STACK_OF(X509)*

How do I use C++ unique_ptr and OpenSSL's STACK_OF(X509)*?

推荐答案

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

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

Then I use it in my code:

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

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

这篇关于unique_ptr和OpenSSL的STACK_OF(X509)*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 15:09