C:\>pip3 install pywin32 Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32
Pypiwin32 is a repackaging of pywin32 to use sane packaging tools (namely
wheels). Its repackaged by the BDFL of the Twisted project. If you use
pip, or virtualenvs (and you should be using pip and virtualenvs, if you are
not, start), use pypiwin32.
C:\>pip3 install pypiwin32
#!/usr/bin/python3 # -*- coding: utf-8 -*- import pythoncom import pywintypes adobe = pywintypes.IID('{DC6EFB56-9CFA-464D-8880-44885D7DC193}') CLSID_IPreviewHandler = '{8895B1C6-B41F-4C1C-A562-0D564250836F}' iid = pywintypes.IID(CLSID_IPreviewHandler) handler = pythoncom.CoCreateInstance( adobe, None, pythoncom.CLSCTX_LOCAL_SERVER, iid) print(handler)
Traceback (most recent call last): File "C:\Projects\pytest\w1.py", line 19, in <module> iid) TypeError: There is no interface object registered that supports this IID
> The document PythonCOM.html says that this is done using a "pyd" module that
> is imported. It is accessed in
> this manner is a C or C ++ module must be created specifically for that
> interface?
Exactly. Note however that the IDispatch
this is true.
> If this is needed, it is there that I can see an example
> of the code for that module? If not, how do I tell Python about the
> interface object associated with the IID?
There are a number of examples in the win32com sources. The most
recent set are in the “internet” and “axcontrols” directory.
Also there are 2 options for generating the C code. One
is to use "makegw" that comes with win32com - it takes a .h file
that has geen itself generated from an IDL file
code. But its not very flexible. There is also a SWIG, which is far
more flexible, but probably not.
.H file generated from an IDL,
then check out "makegw" and the samples I mentioned (which
themselves where generated with makepy)
mk.py
import win32com.makegw.makegw inc = "C:/Program Files (x86)/Windows Kits/10/Include/10.0.14393.0/um/" h = inc + "ShObjIdl.h" win32com.makegw.makegw.make_framework_support(h, "IPreviewHandler")
// *** The input argument hwnd of type "__RPC__in HWND" was not processed *** // Please check the conversion function is appropriate and exists! __RPC__in HWND hwnd; PyObject *obhwnd; // @pyparm <o Py__RPC__in HWND>|hwnd||Description for hwnd
// *** The input argument prc of type "__RPC__in const RECT *" was not processed *** // Please check the conversion function is appropriate and exists! __RPC__in const RECT prc; PyObject *obprc; // @pyparm <o Py__RPC__in const RECT>|prc||Description for prc
#include "rpc.h" #include "rpcndr.h" #include "windows.h" #include "ole2.h" //#define __RPC__in #ifndef __IPreviewHandler_INTERFACE_DEFINED__ #define __IPreviewHandler_INTERFACE_DEFINED__ /* interface IPreviewHandler */ /* [uuid][object] */ #include "prtypes.h" EXTERN_C const IID IID_IPreviewHandler; MIDL_INTERFACE("8895b1c6-b41f-4c1c-a562-0d564250836f") IPreviewHandler : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetWindow( /* [in] */ HWND hwnd, /* [in] */ CRECTPTR prc) = 0; virtual HRESULT STDMETHODCALLTYPE SetRect( /* [in] */ CRECTPTR prc) = 0; virtual HRESULT STDMETHODCALLTYPE DoPreview( void) = 0; virtual HRESULT STDMETHODCALLTYPE Unload( void) = 0; virtual HRESULT STDMETHODCALLTYPE SetFocus( void) = 0; virtual HRESULT STDMETHODCALLTYPE QueryFocus( /* [out] */ HWNDPTR phwnd) = 0; virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator( /* [in] */ MSGPTR pmsg) = 0; }; #endif
prtypes.h
typedef const RECT *CRECTPTR; typedef const MSG *CMSGPTR; typedef MSG *MSGPTR; typedef HWND *HWNDPTR;
mk.py
import win32com.makegw.makegw win32com.makegw.makegw.make_framework_support("preview.h", "IPreviewHandler", bMakeGateway = 0)
C:\Projects\pytest>python mk.py IPreviewHandler
#!/usr/bin/env python from distutils.core import setup, Extension pypacks = "C:/Python/Lib/site-packages/" wdkinc = "C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.14393.0\\" wdklib = "C:\\Program Files (x86)\\Windows Kits\\10\\Lib\\10.0.14393.0\\" pywinsrc = "C:/Projects/Source/pywin32-221/" example_module = Extension('_preview', sources=['PyIPreviewHandler.cpp','prtypes.cpp'], include_dirs=[wdkinc + "ucrt", pywinsrc + "com/win32comext/shell/src", pypacks + "win32/include", pypacks + "win32com/include"], library_dirs=[wdklib + "ucrt\\x86", pypacks + "win32/libs", pypacks + "win32com/libs"] ) setup (name = 'preview', version = '0.1', author = "My", description = """Simple swig example from docs""", ext_modules = [example_module], py_modules = ["preview"], )
C:\Projects\pytest>python.exe setup.py build_ext --inplace >err.txt error: command 'D:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2
PyIPreviewHandler.cpp(46): error C3861: 'PyObject_AsCRECTPTR': identifier not found
CRECTPTR prc; PyObject *obprc; ... if (bPythonIsHappy && !PyObject_AsCRECTPTR( obprc, &prc )) bPythonIsHappy = FALSE; ... PyObject_FreeCRECTPTR(prc);
RECT prc; PyObject *obprc; ... if (bPythonIsHappy && !PyObject_AsRECT( obprc, &prc )) bPythonIsHappy = FALSE; ... //PyObject_FreeCRECTPTR(prc);
#include "shell_pch.h" #include "prtypes.h" BOOL PyObject_AsMSG( PyObject *obpmsg, MSG *msg ) { PyObject *obhwnd; return PyArg_ParseTuple(obpmsg, "Oiiii(ii)", &obhwnd,&msg->message,&msg->wParam,&msg->lParam,&msg->time,&msg->pt.x,&msg->pt.y) && PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&msg->hwnd); } PyObject *PyObject_FromMSG(const MSG *msg) { if (!msg) { Py_INCREF(Py_None); return Py_None; } return Py_BuildValue("Niiii(ii)", PyWinLong_FromHANDLE(msg->hwnd),msg->message,msg->wParam,msg->lParam,msg->time,msg->pt.x,msg->pt.y); } BOOL PyObject_AsRECT( PyObject *ob, RECT *r) { return PyArg_ParseTuple(ob, "iiii", &r->left, &r->top, &r->right, &r->bottom); } PyObject *PyObject_FromRECT(const RECT *r) { if (!r) { Py_INCREF(Py_None); return Py_None; } return Py_BuildValue("iiii", r->left, r->top, r->right, r->bottom); }
LINK : error LNK2001: unresolved external symbol PyInit__preview build\temp.win32-3.6\Release\_preview.cp36-win32.lib : fatal error LNK1120: 1 unresolved externals
PyInit_xxx
similar to the standard name for module initialization, the only question is what should be in it how to register the interface. I had to unravel the PyWin32 sources again and figure out what was needed for a complete build. By analogy with the functions found, PyInit_xxx added his own.
#include "PythonCOMRegister.h" // For simpler registration of IIDs ... // static struct PyMethodDef preview_methods[] = {{NULL}}; PyObject *PyInit__preview(void) { static PyModuleDef _preview_def = { PyModuleDef_HEAD_INIT, "_previewer", "Preview Handler Interface", -1, preview_methods }; PyObject *module=PyModule_Create(&_preview_def); // PyCom_RegisterClientType(&PyIPreviewHandler::type, &IID_IPreviewHandler); return module; }
_preview.cp36-win32.pyd
file was _preview.cp36-win32.pyd
(and here Stirlitz guessed that underlining was superfluous). Install the resulting package.
C:\Projects\pytest>python.exe setup.py install
import _preview
just add import _preview
<source lang="python">#!/usr/bin/python3 # -*- coding: utf-8 -*- import pythoncom import pywintypes import _preview adobe = pywintypes.IID('{DC6EFB56-9CFA-464D-8880-44885D7DC193}') CLSID_IPreviewHandler = '{8895B1C6-B41F-4C1C-A562-0D564250836F}' iid = pywintypes.IID(CLSID_IPreviewHandler) handler = pythoncom.CoCreateInstance( adobe, None, pythoncom.CLSCTX_LOCAL_SERVER, iid) print(handler)
C:\Projects\Python\test>python wincom.py <PyIPreviewHandler at 0x00817770 with obj at 0x00745FFC>
#!/usr/bin/python3 # -*- coding: utf-8 -*- import pythoncom, win32comext import win32comext.propsys.propsys as propsys import win32comext.shell.shell as shellext import pywintypes import _preview from PyQt5.QtCore import * from PyQt5.QtWidgets import * CLSID_IPreviewHandler = '{8895B1C6-B41F-4C1C-A562-0D564250836F}' iid = pywintypes.IID(CLSID_IPreviewHandler) class PreviewWin(QWidget): def __init__(self, parent=None): super().__init__(parent) self.handler = None self.isFirst = True self.topLay = QHBoxLayout(self) self.splitter = QSplitter(self) self.topLay.addWidget(self.splitter) self.model = QFileSystemModel(self) self.model.setRootPath(QDir.currentPath()) self.tree = QTreeView(self.splitter) self.tree.setModel(self.model) cur = self.model.index(QDir.currentPath()) self.tree.setCurrentIndex(cur) self.tree.expand(cur) self.view = QWidget() self.splitter.addWidget(self.tree) self.splitter.addWidget(self.view) self.tree.clicked.connect(self.previewIndex) self.tree.setColumnWidth(0, 200) self.setWindowState(Qt.WindowMaximized) def resizeEvent(self, event): super().resizeEvent(event) if self.handler: self.handler.SetRect(self.view.rect().getRect()); def previewIndex(self, index): try: if self.handler: self.handler.Unload() self.handler = None if not index.isValid(): return filePath = QDir.toNativeSeparators(self.model.filePath(index)) ext = self.model.fileInfo(index).suffix() regPath = "HKEY_CLASSES_ROOT\\." + ext + "\\shellex\\" + CLSID_IPreviewHandler sets = QSettings(regPath, QSettings.NativeFormat) if not sets.contains("."): return classId = sets.value(".") if not classId: return self.handler = pythoncom.CoCreateInstance(classId, None, pythoncom.CLSCTX_LOCAL_SERVER, iid) if not self.handler: return STGM_READ = 0 try: iwfile = self.handler.QueryInterface(propsys.IID_IInitializeWithFile) except: iwfile = None if iwfile: try: iwfile.Initialize(filePath, STGM_READ) except: iwfile = None if not iwfile: try: iwstream = self.handler.QueryInterface(propsys.IID_IInitializeWithStream) except: print(str(sys.exc_info()[1])) iwstream = None if iwstream: iis = shellext.SHCreateStreamOnFileEx(filePath,STGM_READ,0,False) if iis: iwstream.Initialize(iis, STGM_READ) else: return else: print("Can't initialize preview for",filePath) return r = self.view.rect().getRect() self.handler.SetWindow(self.view.winId(), r); self.handler.DoPreview(); self.handler.SetFocus(); except: print(str(sys.exc_info()[1])) if __name__ == '__main__': import sys app = QApplication(sys.argv) w = PreviewWin() w.show() sys.exit(app.exec_())
Source: https://habr.com/ru/post/344086/