创建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目录,从而证明路径问题得到解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值