VS2010下编译x64的dll调用QT4.8.7的模块

400 阅读1分钟

1. 环境

系统win7(64位)+VS2010旗舰版+QT4.8.7

1.1 安装qt-vs-addin插件

可以上官网自行下载安装

1.2 下载QT4.8.7的源码

https://download.qt.io/archive/qt/4.8/4.8.7/
qt-everywhere-opensource-src-4.8.7.zip

2. 编译64位的QT4.8.7(编译的时间会比较长)

2.1 解压qt-everywhere-opensource-src-4.8.7.zip至\QT4.8.7\x64
2.2 打开开始菜单->Microsoft Visual Studio 2010->Visual Studio Tools->Visual Studio x64 Win64 命令提示(2010)
2.3 在命令窗口中先cd到\QT4.8.7\x64目录下,后面依次执行(设置环境变量)
    set PATH += \x64
    set PATH += \ x64\bin
    set LIB += C:\Program Files(x86)\Microsoft SDKs\Windows\v7.0A\Lib
    set INCLUDE += C:\Program Files(x86)\Microsoft SDKs\Windows\v7.0A\Include
2.4配置QT
    configure -platform win32-msvc2010
2.5 开始编译,输入:nmake
2.6 可能遇到的错误
    2.6.1 LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
    解决:将下面目录中(根据VS2010安装的路径)的cvtres.exe先重命名
        D:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64
        D:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin
    重新编译时系统会使用.NET FrameWork下的cvtres.exe

3. 设置VS2010的环境 3.1 启动VS2010,点击菜单Qt->Qt Options 1.png

   点击Add添加64位的QT库
3.2 新建Qt Library工程
    根据向导操作完成后,点击菜单Qt->Qt Project Settings

2.png

将Version切换成刚才编译好的64位的QT

3.3 添加DllMain函数
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpvReserved*/ )
{
    static bool ownApplication = FALSE;
    if ( dwReason == *DLL_PROCESS_ATTACH* )
    {
        ownApplication = QMfcApp::pluginInstance( hInstance );
        //设置QT路径
        char chLibraryPath[512] = {0};
        GetModuleFileNameA(NULL, chLibraryPath, 512);
        //路径转成UTF8,防止中文无法识别
        string strLibraryPath(chLibraryPath), strLibraryPathUTF8;
        StringASCIIToUTF8(strLibraryPath, strLibraryPathUTF8);
        QString qsLibraryPath = QString::fromUtf8(strLibraryPathUTF8.*c_str*());
        int nPos = qsLibraryPath.lastIndexOf("\\");
        qsLibraryPath = qsLibraryPath.left(nPos + 1);
        //Qt插件路径
        qsLibraryPath += "plugins\\";
        QMfcApp::addLibraryPath(qsLibraryPath);
        QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
        QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    }
    if ( dwReason == DLL_PROCESS_DETACH && ownApplication )
        delete qApp;
        
    return TRUE;
}
3.4 导入qmfcapp.h和qmfcapp.cpp
    链接: https://pan.baidu.com/s/16PJFMht6ifpcv7bTvWkJyw 提取码: fe9z

完成