2014-12-27 42 views
-1

我會盡我所能解釋我的問題。所以,我用C/C++編寫的應用程序(客戶端應用程序中的語言無關緊要),它從DLL導入一個函數,例如uint32_t * GetMemoryPointer()。然後它在序列寫入該存儲器指針這樣的:觀看從應用程序接收到的指定內存指針的寫入

uint32_t* ptr = (uint32_t*)GetMemoryPointer(); 
*ptr = 3; 
*ptr = 4; 
*ptr = 1050; 

它這樣做是序列中,而不將該值改變爲DLL的任何信息。是否有可能在DLL中觀看這個值?我試圖做一個線程和循環查找更改,但它不可靠。有更好的解決方案嗎?我對這樣做感興趣:應用程序寫入,DLL發現該值已更改,HOLDS應用程序執行然後解釋此值,然後允許應用程序繼續執行。另一種不需要申請的方式可能會推動堆疊的新價值,但我需要了解每一個變化。我感興趣的平臺是Windows。語言無所謂可能是C或C++。是否有可能實現這一目標?這對我來說非常重要,而且我沒有想法。我不想要代碼,但我希望被告知是否有可能以及需要採用哪種方式。提前致謝。

+1

imho,這是一個XY問題。 http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem你應該解釋你想達到什麼。 – manuell 2014-12-27 15:17:14

+0

我解釋了我想實現的目標,我想實現對DLL中映射的內存小區域(例如4B變量)的監視,並在發生應用程序端更改時得到通知。就這樣。 – 2014-12-27 16:08:19

+0

你沒有解釋爲什麼你想監視一個小區域的內存。您無法控制客戶端應用程序? – manuell 2014-12-27 16:17:43

回答

0

嗯,在我的頭頂,如果你可以將內存標記爲只讀,並且當有人試圖寫入內存時,操作系統將拋出一個異常/錯誤,你必須抓住它。我不知道是否有任何圖書館存在,所以請嘗試使用Google搜索。

1

一個選項是實現一個Value類型,該類型保存要監視的實際數據,並在值更改時使用observer pattern來分派通知。從一個簡單的實現開始,該實現包含所需類型的值(在本例中爲uint32_t)以及賦值運算符,該運算符在操作員更改該值時調用回調。

下面的例子就是這樣做的,它包含一個轉換運算符以允許用其他uint32_t值執行相當數量的操作。您可以對此進行擴展以滿足您的要求,包括提供一整套運營商(operator+,operator/等),以使其更健壯。

#include <iostream> 
#include <vector> 
#include <cstdint> 


class Value 
{ 
    uint32_t value; 
    std::vector<void(*)()> observers; 

public: 

    Value() : value(0) {} 

    // Allows you to register a observer that gets called when 
    // the value changes 
    void RegisterListener(void (*f)()) 
    { 
     observers.push_back(f); 
    } 

    // Conversion operator that allows implicit conversions 
    // from Value to uint32_t. 
    operator uint32_t() const 
    { 
     return value; 
    } 

    Value& operator=(uint32_t newValue) 
    { 
     // Only alert observers if the value is actually changing. 
     if (value != newValue) 
     { 
      value = newValue; 
      for (std::vector<void(*)()>::const_iterator it = observers.begin(); 
       it != observers.end(); 
       ++it) 
      { 
       // Call the observer 
       (*it)(); 
      } 
     } 
     return *this; 
    } 
}; 

void Callback() 
{ 
    std::cout << "value changed\n"; 
} 

int main() 
{ 
    Value value; 
    value.RegisterListener(Callback); 

    // Value held in object can be assigned to a uint32_t due to the 
    // conversion operator. 
    uint32_t original = value; 

    // Change the value see the callback get invoked 
    value = value + 1; 

    // Restore the value to it's original and see the callback get invoked. 
    value = original; 
} 
+0

可悲的是,這不會在我的情況。當從DLL接收到指向(uint32_t *)的指針時,應用程序端的回調函數和運算符不會執行。 – 2014-12-27 16:06:52

+0

@cafebabe_t然後你做錯了。無論您是從共享庫(DLL),應用程序(EXE)還是兩者的組合,此解決方案都能正常工作。 – 2014-12-27 18:21:08