簡體   English   中英

在Visual Studio C ++中將變量從一個項目訪問到另一個項目

[英]Accessing variable from one project to another in visual studio c++

我有一個解決方案,其中有兩個項目。 當我得到代碼時,他們告訴一個項目處理視覺部分,另一個項目處理邏輯部分。 現在,我在窗口中添加了一個按鈕。 為此,我編輯了處理視覺部分的項目。 我對此很陌生,但是在Visual Studio 2010中創建和添加按鈕相當簡單。現在的問題是我想檢測是否從另一個項目中按下了按鈕。 我確定這些項目正在共享一些數據,但是我無法捕獲它們。 現在,我正在更改文件中的值,並從另一個項目中讀取相同的數據,以檢查是否按下了按鈕。 但是我認為有一種更好的方法。 有人可以幫忙嗎?

我認為這兩個項目不會自動共享。 您將必須定義兩個項目進行通信的接口。 例如,在您的解決方案上方,“文件中的值”就是您定義的“接口”。 聽起來您想要實現的目標是分別分離控制器(邏輯部分)和視圖(可視部分),這似乎表明您的項目正在使用MVC模型。

我建議定義一個抽象類(接口),該類定義您要在兩個項目之間進行的交互。 他們只需共享一個頭文件即可。

例如:

// Solution A (Controller - logic part)
// MyUIHandler.h
class IMyUIHandler //You can also use microsoft's interface keyword for something similar.
{
public:
    HRESULT onButtonPressed() = 0; // Note that you can also add parameters to onButtonPressed.
};

HRESULT getMyUIHandler(IMyUIHandler **ppHandler);

然后實現此接口:

// Solustion A (Controller - logic part)
// MyUIHandler.cpp
#include "MyUIHandler.h"
class CMyUIHandler : public IMyUIHandler
{
private:
   // Add your private parameter here for anything you need
public:
    HRESULT onButtonPressed();
}

HRESULT getMyUIHandler(IMyUIHandler **ppHandler)
{
    // There are many ways to handle it here:
    // 1. Define a singleton object CMyUIHandler in your project A. Just return a pointer 
    //    to that object here. This way the client never releases the memory for this 
    //    object.
    // 2. Create an instance of this object and have the client release it. The client 
    //    would be responsible for releasing the memory when it's done with the object. 
    // 3. Create an instance of this object and have a class/method in Solution A release
    //    the memory. 
    // 4. Reference count the object, for example, make IUnknown the parent class of 
    //    IMyUIHandler, and implement the IUnknown interace (which is boiler plate code).
    // Since I don't know your project it's hard for me to pick the most suitable one. 
    ...
    *ppHandler = myNewHandler;
    ...
    return S_OK;
}

CMyUIHandler可以簡單地作為您已經處理某些邏輯的現有類。

在解決方案B中,您應該在一些初始化函數中調用getMyUIHandler,例如UI類的控制器,將其另存為您的成員。 然后,VS為您創建的“單擊按鈕”事件處理程序。

// Solution B (View - visual part)
// MyUIView.h
class MyUIView
{
protected:
    IMyUIHandler *m_pHandler;
}

// MyUIView.cpp
CMyUIView::CMyUIView(...) 
{
    ...
    hr = getMyUIHandler(&m_pHandler);
    // error handler, etc...   
    ...
}

// In the function that is created for you when button is clicked (I'm not sure if I get the signature right below.
void OnClick(EventArgs^ e) 
{
    ...
    hr = m_pHandler->onButtonPressed();
    ...
}

然后,您可以在單擊按鈕后立即傳遞為函數onButtonPressed定義的任何參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM