从Python ctypes加载带有通用Windows平台(UWP)调用的win32dll

2024-06-28 11:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从Python调用通用Windows平台(UWP)API。我试图通过使用ctypes调用包含调用UWPAPI函数的win32 dll来做到这一点。在

总结一下这个过程: Python->;cytpes->;dll->;UWP

我一直在调试它。以下是的工作原理:

  • 创建win32 dll文件并使用 Python ctypes模块
  • 生成包含UWP调用的win32 dll文件(使用指令here)。在
  • 从一个C++ Win32应用程序加载Win32 DLL文件,调用UWP API调用的函数。在

以下是不起作用的地方:

  • 当用Python ctypes加载win32 DLL时,该DLL内的UWP调用;从win32应用程序加载和调用同一DLL时,相同的UWP调用在从ctypes调用时失败。在

Python 3.6.4代码如下所示:

dll = ctypes.CDLL(path_to_dll)
dll.IsKeyboardPresent.restype = ctypes.c_bool
is_keyboard_present = dll.IsKeyboardPresent()

崩溃后的回溯结果如下:

^{pr2}$

dll文件的源代码如下:

#include "stdafx.h"

using namespace Platform;
using namespace Windows::Devices::Input;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;


extern "C" {

__declspec(dllexport) bool IsKeyboardPresent()
{
    bool is_present = 0;

    KeyboardCapabilities^ kbdCapabilities = ref new KeyboardCapabilities();
    is_present = (bool)kbdCapabilities->KeyboardPresent;

    return is_present;
}

再次,从C++中工作,但不是从cType工作。注释掉这一行使它不会从ctypes崩溃:

KeyboardCapabilities^ kbdCapabilities = ref new KeyboardCapabilities();
<> >加载WD32应用程序中的C++片段,加载DLL并调用包含的函数,没有错误:

typedef int(__stdcall *ISKEYBOARDPRESENT)();

HINSTANCE hinstLib;
ISKEYBOARDPRESENT IsKeyboardPresentProc;
BOOL fFreeResult;

bool is_keyboard_present;

hinstLib = LoadLibrary(TEXT("Win32Project2.dll"));
if (NULL != hinstLib) {
    IsKeyboardPresentProc = (ISKEYBOARDPRESENT)GetProcAddress(hinstLib, "IsKeyboardPresent");
    if (NULL != IsKeyboardPresentProc)
    {
        is_keyboard_present = (IsKeyboardPresentProc)();
    }
    fFreeResult = FreeLibrary(hinstLib);

}  

这是在带有Visual Studio 2015和32位Python 3.6.4的Windows 10上运行的

感觉我离得很近,但是被困在这里了。一个原因是,Windows错误代码太过笼统,无法为我指明方向。另外,当我从Python调用DLL时,它不会到达我在visualstudio中设置的调试点。在


Tags: 文件iswindowsctypesnamespacebooldllusing