簡體   English   中英

掌握 C++ std::function 語法的問題

[英]Problems grasping C++ std::function syntax

我無法將消息從 DLL 的日志記錄 function 發送到客戶端的日志記錄 function。 我可以使用這樣的 function 指針:

DLL:

class InnerLogger
{
public:
    static std::function<void(const std::string& message, int level)> loggerCallback;
    static std::stringstream logMsg;
    static int logSend(LogLevel logLevel);
};

void setLoggingFunction(const std::function<void(const std::string& message, int level)>& logFunction)
{
    InnerLogger::loggerCallback = logFunction;
}

客戶:


void outerLogger(const std::string& message, int level)
{
  // display/save messages
}

main()
{
    std::function<void(const std::string& message, int level)> logFunctionPtr = outerLogger;
    setLoggingFunction(logFunctionPtr);
}

我可以使用 InnerLogger::logSend 和 outerLogger 來接收它。

但是當“外部”記錄器是 class 成員時,我做錯了:

(DLL 不變)

客戶:

class OuterLogger
{
public:
    OuterLogger();
    ~OuterLogger();

    void logFunction(const std::string& message, int level);
};

void OuterLogger::logFunction(const std::string& message, int level)
{
    // display/save messages
}

main()
{
    OuterLogger outerLogger;
    std::function<void(const std::string& message, int level)> logFunctionPtr = outerLogger.logFunction;
    setLoggingFunction(logFunctionPtr);
}

以下是 class 如何綁定到 function 的示例:

#include <iostream>
#include <functional>

class A {
    public:
    int x = 1;
    void func() {
        std::cout << x;
    }
    ~A() {
        x = 2; // just to test the destructor
    }
};

int main()
{
    std::function<void(void)> f;

    {
        A a;
        f = std::bind(&A::func, a); // do not bind &a because it will be out of scope
    }

    f();

    return 0;
}

在您的情況下,您可以使用:

std::function<void(const std::string& message, int level)> logFunctionPtr = std::bind(&OuterLogger::logFunction, outerLogger, std::placeholders::_1, std::placeholders::_2);

您可以使用 lambda function 代替綁定:

std::function<void(const std::string&, int)> logFunctionPtr =
    [outerLogger](const std::string& message, int level) mutable {
        outerLogger.logFunction(message, level);
    };

我嘗試了幾種不同的方法來傳遞 function 指針,但都沒有奏效,但結果證明該代碼沒有任何問題。

當我使用成功被 DLL 記錄器接受的任何形式的代碼時,調試顯示它會立即 go null 之后。

我正在使用 VS 的測試資源管理器。 事實證明,一些經過測試的進程實例沒有正確關閉,所以我把 testhost 進程卡在了后台,我認為地址不知何故被弄亂了。

線索是間歇性無法多次運行測試,以及調試模式下的非常奇怪的行為 - 執行標記向后跳並產生神秘的 WINRT_ASSERT(.is_sta()) 異常。 答案是運行 Process Explorer 並檢查 VS 下的卡住進程。 (有點煩人的是 VS 無法告訴我它正在測試的進程有問題,但是 nvm)

我的代碼使用 WinML 庫。 如果我在 CPU 模式下運行,那很好。 如果我使用 GPU 它會卡在關機狀態,所以我需要找出原因。

感謝大家的幫助。

編輯:我最初的假設是,將代碼從非對象移動到 object 是一個問題——這完全錯誤。 代碼的原始非對象版本之所以有效,是因為它位於演示客戶端中,這是一個調用 DLL 的單個可執行控制台程序,它從未受到狡猾的關閉問題的影響。 在具有多個實例的單元測試套件中,它成為了一個問題。

暫無
暫無

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

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