C++ - 类方法不会从 dll 导出 (VS - win)

C++ - class method's won't to export from dll (VS - win)

本文关键字:VS 导出 win 类方法 C++ dll      更新时间:2023-10-16

我在Visual Studio中创建了dll类型的示例C++项目。它包含头文件SqlLtDb.h:

 using namespace std;
    // This class is exported from the SqlLtDb.dll
    class CSqlLtDb {
    public:
        CSqlLtDb(char *fileName);
        ~CSqlLtDb();
        // TODO: add your methods here.
        bool SQLLTDB_API open(char* filename);
        vector<vector<string>> SQLLTDB_API query(char* query);
        bool SQLLTDB_API exec(const char* query);
        void SQLLTDB_API close();
        int SQLLTDB_API getNameOfClass();
    private:
        sqlite3 *database;
    };
extern "C" SQLLTDB_API CSqlLtDb* getInstanceCSblLtDb();
extern SQLLTDB_API int nSqlLtDb;
extern "C" SQLLTDB_API int fnSqlLtDb();

和在SqlLtDb.cpp方法实现如下(我只显示两个实现):

...
int SQLLTDB_API CSqlLtDb::getNameOfClass()
{
    return 777;
}
extern "C" SQLLTDB_API CSqlLtDb* getInstanceCSblLtDb()
{
    CSqlLtDb* instance = new CSqlLtDb("");
    return instance;
}

SqlLtDb.def文件看起来像这样:

LIBRARY "SqlLtDb"
EXPORTS
getInstanceCSblLtDb
open
query
exec
close
getNameOfClass

SqlLtDb。lib文件是由lib命令生成的,使用上面的.def文件。这是我的SqlLtDb.dll文件

现在我想把这个文件包含到我的consoleApplication应用程序中。ConsoleApplication在VS 2008中。我设置:

Properties->Configuration Properties->Linker->Input->Additional Dependencies : SqlLtDb.lib;

Properties->Configuration Properties->Linker->General->Additional Library Directories: E:PMSqlLtDbRelease;

运行库设置为:多线程调试DLL (/MDd)(我没有改变它)。

我将文件:SqlLtDb.dll, SqlLtDb.lib, SqlLtDb.def, sqlite3.dll复制到生成consoleApplication.exe的Debug文件夹中。并且我将SqlLtDb.h文件添加到存储consoleApplication's源文件的文件夹中。

consoleApplication的main函数如下:

#include "stdafx.h"
#include "SqlLtDb.h";
int _tmain(int argc, _TCHAR* argv[])
{
    CSqlLtDb* mySqlClass = getInstanceCSblLtDb();  // here is ok, this method is 
                                                   // exported rigth
    mySqlClass->open("");  // here is error whit open method
    return 0;
}

当我编译这段代码时,我得到错误:

Error 1 error LNK2019: unresolved external symbol "__declspec(dllimport) public: 
bool __thiscall CSqlLtDb::open(char *)" (__imp_?open@CSqlLtDb@@QAE_NPAD@Z) 
referenced in function _wmain consoleApplication.obj consoleApplication

方法getInstanceCSblLtDb导出成功,但问题是类的导出方法。我不会导出所有的类,最好是导出指向类的指针。

谢谢

您需要使用__declspec(dllexport)在DLL中导出该类,然后使用__declspec(dllimport)在链接代码中导入该类。例子:

class SQLLTDB_API CSqlLtDb {
    ...
};

您不需要为每个成员生成SQLLTDB_API,只需要为类生成SQLLTDB_API—链接器将为您生成每个方法的导出。