U
U
undeadter2017-01-28 17:22:15
C++ / C#
undeadter, 2017-01-28 17:22:15

C++ how to encapsulate a global function in an object?

#include <physfs/physfs.h>
int main() {
    PHYSFS_init(NULL);
    PHYSFS_addToSearchPath("res.data", 1);
    
    if (PHYSFS_exists()) {
        /////////////////
       // PHYSFS_exists доступна во всем коде, даже если вызывать PHYSFS_init() в классе
       /////////////////
    }
}

How to make the library initialized only inside the object?
For example:
in the first PHYSFS_addToSearchPath("res.data", 1);
and in the second PHYSFS_addToSearchPath("res2.data", 1);

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Rou1997, 2017-01-28
@Rou1997

Use its OOP version if it is Qt, or look towards its code, if it does not support handles ("handle"), then they must be added.

J
Jacob E, 2017-01-28
@Zifix

Singleton?

M
Mercury13, 2017-01-28
@Mercury13

What do you have in mind? Initialize and close the library as objects appear-disappear? Here is my code (works with cURL, but understandable).
What is its meaning? As soon as the cURL object is required for the first time, we initialize the global object. Now it's likely that cURL will be destroyed with its destructor. But if in some thread the cURL object will live too long - nothing, let's wait.
(Attention, there is a race here if two cURL objects are required at the same time. We don’t need this, but if it happens, protect it according to the Singleton principle.)

namespace curl {

    std::atomic<size_t> nLib(0);

    class _Lib
    {
    public:
        bool isIn = false;
        ~_Lib();
    };

    _Lib lib;

    void addLib()
    {
        int q = ++nLib;
        if (q == 1) {
            lib.isIn = true;
            q = ++nLib;
            curl_global_init(CURL_GLOBAL_ALL);
        }
        //std::cout << "Added lib, now " << q << std::endl;
    }

    void releaseLib()
    {
        int q = --nLib;
        if (q == 0) {
            //std::cout << "Cleaned up lib" << std::endl;
            curl_global_cleanup();
        } else {
            //std::cout << "Released lib, now " << q << std::endl;
        }
    }

    _Lib::~_Lib()
    {
        if (isIn)
            releaseLib();
    }

}

curl::Curl::Curl()
{
    addLib();
    fData.handle = curl_easy_init();
}

curl::Curl::~Curl()
{
    if (fData.handle)
        curl_easy_cleanup(fData.handle);
    releaseLib();
}

V
Vasily Melnikov, 2017-01-30
@BacCM

A separate cpp/h
#include module is included only in this h
And all the necessary functions have their own wrappers, with an additional flag check to see if init was called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question