Qt设置生成exe为当前输出目录的工具类(原理win API调用)卲发所写

当前执行目录:程序调试输出的目录和exe文件执行的目录不一样

程序调试输出的目录:是代码执行的文件所在目录

exe文件执行目录:与exe同级。


#ifndef _AF_CD_H
#define _AF_CD_H

/* AfCd
   用于设置进程的"当前目录"

   作者:邵发
   版本:2016-01-05
   最新版本请在官网 http://afanihao.cn 上获取
*/

#include <string>
using std::string;

class AfCd
{
public:
	// 得到exe文件所在的目录 
	static string exeLocation(char seperator='\\');

	// 切换到目标位置 
	static void cd(const string& targetDir);

	// 切换到exe所有的位置 
	static void cd();
};

#endif




#ifdef _WIN32


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#include <windows.h>
#include "AfCd.h"


string AfCd::exeLocation(char seperator)
{
	// 得到exe文件的全路径
	char buf[512]={0};
	GetModuleFileNameA(NULL, buf, 512);


	// 替换分隔符
	string filePath = buf;
	if(seperator != '\\') //windows下默认是反斜线
	{
		for(int i=0; i<filePath.length(); i++)
		{
			if(filePath[i] == '\\') 
				filePath[i] = seperator;
		}
	}


	// 去除文件名,得到纯目录 
	int pos = filePath.rfind(seperator);
	string cd = filePath.substr(0, pos + 1);	
	return cd;
}


void AfCd::cd(const string& dir)
{
	SetCurrentDirectoryA(dir.c_str());
}


void AfCd::cd()
{
	string where = exeLocation('\\');
	cd(where);
}




#endif





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Qt的QLibrary类来调用Win32编写的DLL。以下是一些基本步骤: 1. 在Qt项目添加一个新的类,例如MyWin32DLLWrapper。 2. 在MyWin32DLLWrapper.h文件,添加以下代码: ``` #ifndef MYWIN32DLLWRAPPER_H #define MYWIN32DLLWRAPPER_H #include <QLibrary> typedef int (*MyWin32DLLFunction)(int); class MyWin32DLLWrapper { public: MyWin32DLLWrapper(); int myWin32DLLFunction(int param); private: QLibrary m_library; MyWin32DLLFunction m_myWin32DLLFunction; }; #endif // MYWIN32DLLWRAPPER_H ``` 3. 在MyWin32DLLWrapper.cpp文件,添加以下代码: ``` #include "MyWin32DLLWrapper.h" MyWin32DLLWrapper::MyWin32DLLWrapper() : m_library("myWin32DLL.dll"), // 替换成实际的DLL文件名 m_myWin32DLLFunction(nullptr) { m_myWin32DLLFunction = (MyWin32DLLFunction)m_library.resolve("myWin32DLLFunction"); } int MyWin32DLLWrapper::myWin32DLLFunction(int param) { if (m_myWin32DLLFunction) { return m_myWin32DLLFunction(param); } else { return -1; // 调用失败 } } ``` 4. 在Qt项目使用MyWin32DLLWrapper类来调用Win32编写的DLL,例如: ``` MyWin32DLLWrapper wrapper; int result = wrapper.myWin32DLLFunction(123); ``` 其123是传递给DLL函数的参数,result是DLL函数返回的结果。 需要注意的是,在使用QLibrary类加载DLL文件时,需要指定DLL文件的完整路径或者将DLL文件放在系统路径下(例如C:\Windows\System32)。另外,需要在Qt项目的.pro文件添加以下代码: ``` LIBS += -L"path/to/dll" -lmyWin32DLL ``` 其path/to/dll是DLL文件的路径,myWin32DLL是DLL文件的名称(不包括扩展名)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值