c++生成动态库 python通过调用dll最小化窗口启动应用程序

python的subproce.Popen()可以打开exe,但是无法最小化打开,所以只能通过复杂的办法了。
如果调用的exe没有界面,则可使用该方法。

1、C++写法
参考各种输入参数C++写法
通过传入应用程序绝对路径启动。(字符串:.exe+参数)

#include <math.h>
#include "windows.h"
#include <C:\Users\Administrator\AppData\Local\Programs\Python\Python36\include\Python.h>
#define EXPORT_HELLO_DLL

#ifdef EXPORT_HELLO_DLL
#define HELLO_API __declspec(dllexport)
#else
#define HELLO_API __declspec(dllimport)
#endif

extern "C"
{
    HELLO_API void useexe(char * str);
}

HELLO_API void useexe(char * str){
    WinExec(str, SW_SHOWMINNOACTIVE);   
    //有不同的启动方式
}

2、生成动态库
安装MinGW,将bin路径添加至系统环境变量。
然后在终端输入:

g++ -fPIC test.cpp(cpp绝对路径) –o test.dll(保存绝对路径) –shared

3、python调用打开exe

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from ctypes import c_char_p, cdll, c_int, c_char, Structure, POINTER, byref

if __name__ == '__main__':
    commd = r"C:\a.exe  1"   #不能有中文
    dll = cdll.LoadLibrary(r'./temp.so')
    
    start_exe = dll.useexe
    start_exe.argtype = [POINTER(c_char)]   #配置输入参数类型
        
    commd = (c_char * 100)(*bytes(commd, 'utf-8'))
    # cast(commd, POINTER(c_char))
    start_exe(commd)   #异步启动,程序运行结束,启动的应用程序继续运行

4、python关闭exe

    import win32com.client
    process_name = 'a.exe'
    wmi = win32com.client.GetObject('winmgmts:')
    processCodeCov = wmi.ExecQuery('select * from Win32_Process where name=\"%s\"' %(process_name))
    if len(processCodeCov) > 0:
        os.system(r'taskkill /F /IM %s' % (process_name))

5、可能报错
a)

1.d:\SY\cgg_code\test.cpp:3:10: fatal error: Python.h: No such file or directory

找到Python.h,添加:

#include <C:\Users\Administrator\AppData\Local\Programs\Python\Python35\include\Python.h>

b)

 D:/software/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/cmath:1121:11: error: '::hypot' has not been declared
   using ::hypot;

原因:在pyconfig的header file中,hypot被重命名为_hypot,cmath调用了hypot。
解决方法:在#include <C:\Users\Administrator\AppData\Local\Programs\Python\Python35\include\Python.h>之前#include <math.h>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值