路径问题分为Qt搜索库路径和QtQuick组件路径。
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <windows.h>
#include <Poco/Path.h>
#include <Poco/String.h>
using namespace std;
bool GetSelfModulePath(char* path)
{
MEMORY_BASIC_INFORMATION mbi;
HMODULE dllHandle = ((::VirtualQuery(GetSelfModulePath, &mbi, sizeof(mbi)) != 0) ? (HMODULE)mbi.AllocationBase : NULL);
TCHAR t_path[MAX_PATH] = { 0 };
GetModuleFileNameW(dllHandle, t_path, MAX_PATH);
int iLength = WideCharToMultiByte(CP_ACP, 0, t_path, -1, NULL, 0, NULL, NULL);
return WideCharToMultiByte(CP_ACP, 0, t_path, -1, path, iLength, NULL, NULL);
}
extern "C" void __declspec(dllexport) run();
void run()
{
::MessageBox(0, 0, 0, 0);
//设置Qt的的DLL搜索路径
QStringList pathes = QGuiApplication::libraryPaths();
char path[1024];
memset(path, 0, 1024);
GetSelfModulePath(path);
Poco::Path p(path);
p.parent();
string stdPath = p.parent().toString();
Poco::replaceInPlace(stdPath, "\\", "/");
QString m_currentPath = QString::fromStdString(stdPath);
pathes << m_currentPath;
QGuiApplication::setLibraryPaths(pathes);
//设置QML模块搜索路径
int _argc = 1;
char* _argv[1];
_argv[0] = new char[1]{ 0 };
QGuiApplication app(_argc, _argv);
QQuickView qview;
// 设置qml引用控件的导入路径
qview.engine()->addImportPath(m_currentPath);
qview.setSource(QUrl("qrc:/main.qml"));
qview.show();
app.exec();
}
以上代码假设Qt DLL中有导出函数run,通过下面的方式调用run函数:
#include <windows.h>
#include <iostream>
using namespace std;
typedef void(*run)();
int main() {
HMODULE m =LoadLibraryEx(LR"(release\QtEnvironmentTest.dll)", 0, LOAD_WITH_ALTERED_SEARCH_PATH);
if (m == nullptr) {
cout << "Load Library Fall" << endl;
m = LoadLibraryEx(LR"(QtEnvironmentTest.dll)", 0, LOAD_WITH_ALTERED_SEARCH_PATH);
if (m == nullptr) {
cout << "Load Library Fall2" << endl;
return -1;
}
}
run r = (run)GetProcAddress(m, "run");
r();
return 0;
}
可以将dll放置在当前目录,也可以放置在上一级release目录,从而证明路径问题得到解决。