Methods of sharing class instances between processes

試著忘記壹切 提交于 2020-01-02 09:11:24

问题


I have written a C++ class that I need to share an instance of between at least two windows processes. What are the various ways to do this?

Initially I looked into #pragma data_seg only to be disappointed when I realised that it will not work on classes or with anything that allocates on the heap.

The instance of the class must be accessible via a dll because existing, complete applications already use this dll.


回答1:


You can potentially use memory-mapped files to share data between processes. If you need to call functions on your object, you'd have to use COM or something similar, or you'd have to implement your own RPC protocol.




回答2:


Look into Boost::interprocess. It takes a bit of getting used to, but it works very well. I've made relatively complex data structures in shared memory that worked fine between processes.

edit: it works with memory-mapped files too. The point is you can use data in a structured way; you don't have to treat the memory blocks (in files or shared memory) as just raw data that you have to carefully read/write to leave in a valid state. Boost::interprocess takes care of that part and you can use STL containers like trees, lists, etc.




回答3:


You can use placement new to create the object in a shared memory zone. As long as the object doesn't use any pointers, that sould be fine.




回答4:


Is it a POD or do you need to be able to share a single instance across processes? Have you considered using the Singleton pattern (static initialization version, for thread safety reasons)? You will need to use Mutexes as well to protect concurrent writes and stuff.

On Windows, you can use COM as well.



来源:https://stackoverflow.com/questions/581773/methods-of-sharing-class-instances-between-processes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!