【问题标题】:Callback function does't work Multi-threaded Debug (/ MTd)回调函数不起作用 多线程调试 (/MTd)
【发布时间】:2013-03-15 18:08:28
【问题描述】:

我需要创建一个适用于回调函数的 dll。 当我在项目属性中设置 Runtime Libary = Multi-threaded Debug (/MTd) 时, 它会生成此错误消息:

但是当我设置 Runtime Libary = Multi-threaded Debug DLL (/MDd) 时,应用程序可以完美运行

看看我的 DLL:

callbackproc.h

#include <string>

#ifdef CALLBACKPROC_EXPORTS
#define CALLBACKPROC_API __declspec(dllexport)
#else
#define CALLBACKPROC_API __declspec(dllimport)
#endif

// our sample callback will only take 1 string parameter
typedef void (CALLBACK * fnCallBackFunc)(std::string value);

// marked as extern "C" to avoid name mangling issue
extern "C"
{
    //this is the export function for subscriber to register the callback function
    CALLBACKPROC_API void Register_Callback(fnCallBackFunc func);
}

callbackpro.cpp

#include "stdafx.h"
#include "callbackproc.h"
#include <sstream>

void Register_Callback(fnCallBackFunc func)
{
    int count = 0;

    // let's send 10 messages to the subscriber
    while(count < 10)
    {
        // format the message
        std::stringstream msg;
        msg << "Message #" << count;

        // call the callback function
        func(msg.str());

        count++;

        // Sleep for 2 seconds
        Sleep(2000);
    }
}

stdafx.h

#pragma once

#include "targetver.h"    
#define WIN32_LEAN_AND_MEAN           
// Windows Header Files:
#include <windows.h>

我使用 dll 的应用程序

#include <windows.h>
#include <string>

#include "callbackproc.h"

// Callback function to print message receive from DLL
void CALLBACK MyCallbackFunc(std::string value)
{
    printf("callback: %s\n", value.c_str());
}

int _tmain(int argc, _TCHAR* argv[])
{
    // Register the callback to the DLL
    Register_Callback(MyCallbackFunc);

    return 0;
}

我哪里错了? 坦克!

【问题讨论】:

  • 您是否按“重试”(Repetir)来调试应用程序?你发现了什么?
  • 请为您的应用和 DLL 指定运行时规范 (MTd,MDd)
  • 我得到另一个错误 = Exoression _pFristBlock == pHead 并且应用遵循流程。但是当函数再次调用时,我们又回到了同样的问题
  • 您正在跨编译单元复制std::string(从您的应用程序过渡到 DLL)。除非 both 是使用 相同 构建配置构建的,否则您就是在自找麻烦。请记住,标准库没有正式的ABI。您的应用程序很可能是使用 /MDd 构建的(使用多线程调试 DLL 运行时)。如果您的 DLL 构建不完全相同,那么您正在使用两个不同的堆管理器并在自取其辱。不要跨 PE 转换传递标准库对象。

标签: c++ dll callback microsoft-runtime-library visual-studio-2010


【解决方案1】:

在我看来是跨 DLL 边界传递 std 类型(在本例中为 std::string)的经典问题。

作为最佳实践,跨 DLL 边界仅传递“本机”数据类型,我敢肯定,如果您从

更改原型,99%
typedef void (CALLBACK * fnCallBackFunc)(std::string value);

typedef void (CALLBACK * fnCallBackFunc)(const char* value);

无论您的底层运行时如何,您的代码都可以正常工作

【讨论】:

  • .. 并使用func(str.c_str()) 调用;
猜你喜欢
  • 2014-03-23
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多