創建QtQuick DLL和引用DLL可能面臨的路徑問題以及解決方案。

路徑問題分爲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目錄,從而證明路徑問題得到解決。

發佈了13 篇原創文章 · 獲贊 3 · 訪問量 1049
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章