进程间通信(1) dll 实现进程的内存共享
1. 兩個(gè)進(jìn)程訪問(wèn)同一個(gè)dll
2.寫入時(shí)復(fù)制(CopyOnWrite,簡(jiǎn)稱COW)思想
如果有多個(gè)調(diào)用者(Callers)同時(shí)訪問(wèn)相同的資源(如內(nèi)存或者是磁盤上的數(shù)據(jù)存儲(chǔ)),他們會(huì)共同獲取相同的指針指向相同的資源,直到某個(gè)調(diào)用者修改資源內(nèi)容時(shí),系統(tǒng)才會(huì)真正復(fù)制一份專用副本(private copy)給該調(diào)用者, 只有更新操作,才會(huì)去復(fù)制一份新的數(shù)據(jù)并更新替換,否則都是訪問(wèn)同一個(gè)資源。
3. 注意點(diǎn)
3.1 不能傳指針作共享,每進(jìn)程有自己的內(nèi)存空間。
Each process gets its own address space. It is very important that pointers are never stored in a variable contained in a shared data segment. A pointer might be perfectly valid in one application but not in another.
3.2. 共享變量得初始化Any variables in a shared data segment must be statically initialized.
4.1 dll:
#pragma data_seg("MySec") int nDate = 0; #pragma data_seg() #pragma comment(linker,"/section:MySec,rws") _declspec(dllexport) void setIntData(int nDate1) {nDate = nDate1; }_declspec(dllexport) int getIntData() {return nDate; }4.2 exe中的代碼:
void testSetFunc() {HINSTANCE hInst;hInst = LoadLibrary("Dll1.dll");typedef void (*setIntData)(int nDate1);setIntData setIntDataFunc = (setIntData)GetProcAddress(hInst, MAKEINTRESOURCE(5));if (!setIntDataFunc){return;}setIntDataFunc(66); }void testGetFunc() {HINSTANCE hInst;hInst = LoadLibrary("Dll1.dll");typedef int (*getIntData)();getIntData getIntDataFunc = (getIntData)GetProcAddress(hInst, MAKEINTRESOURCE(2));if (!getIntDataFunc){return;}int n = getIntDataFunc();char ch[256] = "\0";sprintf_s(ch, "%d", n);MessageBox(g_hWnd, ch, "f", MB_OK); } 4.3在兩個(gè)進(jìn)程exe中分別調(diào)用testSetFunc,testGetFunc將得到同一個(gè)結(jié)果。
【引用】
[1]: 代碼地址 https://github.com/thefistlei/os
[2]: How do I share data in my DLL with an application or with other DLLs https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/h90dkhs0(v=vs.90)?redirectedfrom=MSDN
總結(jié)
以上是生活随笔為你收集整理的进程间通信(1) dll 实现进程的内存共享的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 区块链BaaS云服务(5)金丘科技 海星
- 下一篇: 区块链BaaS云服务(7)微软Azure