Python 3 中调用 COM 的库文件

这篇博客探讨了Python 2.x到3.x中COM接口支持的变化,特别是win32 COM包在3.x时代的缺失。作者分享了一段Python 3代码,用于调用COM库文件,虽然没有详细注释,但简化了复杂Interface的定义。
摘要由CSDN通过智能技术生成

在 Python 2.x 时代貌似有支持 COM的。 http://svn.python.org/projects/ctypes/tags/release_0_6_2/ctypes/win32/com/__init__.py 这个 win32 的 COM 包到了 3.x 时代就不见了。从那里参考和借鉴了很多,也被误导了很多,因为从 2.x 到 3.x 变化很大,而且那个包里面也有很多地方写得不够好。

闲话少说,直接贴代码。没加注释,也省略一些复杂 Interface 的定义。

import atexit
import ctypes
import ctypes.wintypes
import traceback
import uuid

HRESULT	= ctypes.wintypes.DWORD
LCID	= ctypes.wintypes.DWORD
DISPID	= ctypes.wintypes.INT
SCODE	= ctypes.wintypes.DWORD
VARTYPE	= ctypes.c_ushort

S_OK	= 0

def __init__():
	ctypes.oledll.ole32.CoInitialize(None)
	atexit.register(ctypes.oledll.ole32.CoUninitialize)

__init__()

class GUID(ctypes.Structure):
	_fields_ = [("Data1", ctypes.wintypes.DWORD),
				("Data2", ctypes.wintypes.WORD),
				("Data3", ctypes.wintypes.WORD),
				("Data4", ctypes.wintypes.BYTE*8)]

	def __init__(self, name=None):
		iid = uuid.UUID(name)
		self.Data1 = iid.time_low
		self.Data2 = iid.time_mid
		self.Data3 = iid.time_hi_version
		data = iid.bytes
		for i in range(8):
			self.Data4[i] = ctypes.wintypes.BYTE(data[8+i])

	def __str__(self):
		s = (ctypes.c_wchar*39)()
		ctypes.oledll.ole32.StringFromGUID2(ctypes.byref(self), s, 39)
		return s.value

REFGUID = REFIID = RIID = ctypes.POINTER(GUID)

class _InterfaceMetaclass(type(ctypes.Structure)):
	def __new__(cls, name, bases, kwds):
		if "_methods_" in kwds and "_methods_" in bases[0].__dict__:
			kwds["_methods_"] = bases[0]._methods_+kwds["_methods_"]
	
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值