【问题标题】:LNK2001 unresolved external when importing functions from MFC DLL从 MFC DLL 导入函数时 LNK2001 无法解析外部
【发布时间】:2011-11-30 20:34:02
【问题描述】:

我创建了一个 MFC DLL 并导出了函数,例如文件 SerialPort.h:

class CSerialPortApp : public CWinApp
{
public:
    CSerialPortApp();

    __declspec(dllexport) int SWrite(unsigned char* toSend, int len);
};

在我的 MFC 应用程序中,我想调用 SerialInterface.h 中的函数,我已包含 DLL 中的“SerialPort.h”并调用:

__declspec(dllimport) int SWrite(unsigned char* toSend, int len);

class SerialInterface
{
public:

};

例如。

我已将 SerialPort.lib 文件添加到我的链接器包含但当我尝试编译时我得到了

error LNK2001: unresolved external symbol "__declspec(dllimport) int __cdecl SWrite(unsigned char*, int)" (__imp_?SWrite@@YAHPAEH@Z)

我对造成这种情况的原因感到困惑,我已尝试重建所有内容,但似乎没有任何帮助?

感谢您的帮助!

【问题讨论】:

    标签: visual-c++ mfc linker dllimport declspec


    【解决方案1】:

    您在类中使用 __declspec(dllexport)?

    您可以从 dll 或可能包含任何函数的整个类中导出全局函数。您不必从类中导出选定的成员函数,我什至不知道它是如何工作的。

    有点奇怪,您没有从 dll 中正确导出 SerialPort 类(根据您的代码),但您可以在应用程序中使用它并调用它的成员函数!?我有点困惑。

    【讨论】:

    • 是的,但是我不想导出类中的所有变量,所以这种方式只允许访问我想要的函数......或者至少我认为它是这样工作的!跨度>
    【解决方案2】:

    好吧,我找到了一个可行的替代方案,我相信我执行不正确。

    我在我的 DLL 中添加了一个不是 CWinApp 类的新类:

    class SerialPort
    {
    public:
        __declspec(dllexport) SerialPort(void);
        __declspec(dllexport) virtual ~SerialPort(void);
    
        __declspec(dllexport) int SWrite(unsigned char* toSend, int len);
    };
    

    然后在我的应用程序以及 lib 和 dll 等中包含此标头。

    然后我将包含的头文件放在主 CDialog 头中,但重要的是不需要导入任何函数:

    #include "SerialPort.h"
    
    class CPPUDlg : public CDialog
    {
    public:
        CPPUDlg(CWnd* pParent = NULL); // standard constructor
    
        SerialPort objSerialPort;
    

    然后在我的代码中我只是调用

    objSerialPort.SWrite(toSend, len);
    

    我没有使用 dllimport 来导入我认为我需要的函数,但它现在可以工作了!

    希望这对可能遇到类似问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 2011-05-06
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 2013-09-11
      相关资源
      最近更新 更多