Sharing memory between modules

前端 未结 4 1476
南方客
南方客 2020-12-13 22:36

I was wondering how to share some memory between different program modules - lets say, I have a main application (exe), and then some module (dll). They both link to the sam

4条回答
  •  青春惊慌失措
    2020-12-13 22:55

    For use from the current process only, you don't need to devise any special function or structure.

    You could do it even without any function but it is more safe and cross platform friendly to define set of functions providing access to the shared data. And these functions could be implemented by the common static library.

    I think, only concern of this setup is that: "Who will own the data?". There must exist one and only one owner of the shared data.

    With these basic idea, we could sketch the API like this:

    IsSharedDataExist     // check whether of not shared data exist
    
    CreateSharedData      // create (possibly dynamically) shared data
    
    DestroySharedData     // destroy shared data
    
    ... various data access API ...
    

    Or C++ class with the Singleton pattern will be appropriate.


    UPDATE

    I was confused. Real problem can be defined as "How to implement a Singleton class in a static library that will be linked with multiple dynamic loading library (will be used in the same process) in platform independent way".

    I think, basic idea is not much different but make sure the singleton is the really single is the additional problem of this setup.

    For this purpose, you could employ Boost.Interprocess.

    #include 
    #include 
    ...
    boost::interprocess::named_mutex* singleton_check = 0;
    
    // in the Create function of the singleton
    try {
        singleton_check = new boost::interprocess::named_mutex(boost::interprocess::create_only, "name_of_the_mutex" );
        // if no exception throw, this is the first time execution
    }
    catch (...)
    {
    }
    

    Freeing the named_mutex is as simple as delete singleton_check.


    UPDATE#2

    Another suggestion.

    I think, we should not place shared data in the common static library. If we can not ensure globally unique data, it is not only tricky platform dependent implementation problems but also waste of memory and global resources.

    If you prefer static library implementation you should make two static libraries. One for the server/creator of the shared data, one for users of that shared data. Server library define and provide access to the Singleton. Client library provide various data access method.

    This is effectively same as the Singleton implementation without static libraries.

提交回复
热议问题