共計 1136 個字符,預計需要花費 3 分鐘才能閱讀完成。
要在 Python 中生成 COM 組件,可以使用 pywin32 庫。下面是一個簡單的示例,演示了如何創建一個 COM 組件:
import win32com.client
import pythoncom
from win32com.server import register
class MyCOMComponent:
_reg_clsid_ = "{YOUR-CLSID}" # 替換為你的 CLSID
_reg_desc_ = "My COM Component"
_reg_progid_ = "MyCOMComponent"
_public_methods_ = ['hello'] # 可調用的公共方法
def hello(self):
return "Hello from My COM Component!"
if __name__ == "__main__":
# 注冊 COM 組件
register.UseCommandLine(MyCOMComponent)
# 創建 COM服務器
pythoncom.CoInitialize()
clsid = pythoncom.CreateGuid()
server = win32com.server.register.UseCommandLine(MyCOMComponent, clsid=clsid)
# 運行 COM 服務器
pythoncom.CoInitialize()
pythoncom.CoInitializeSecurity(None, None, None, None, pythoncom.RPC_C_AUTHN_LEVEL_NONE, pythoncom.RPC_C_IMP_LEVEL_IMPERSONATE, None, pythoncom.EOAC_NONE)
server._InitServer()
# 進入消息循環
pythoncom.PumpMessages()
上述代碼定義了一個名為 MyCOMComponent 的類,該類實現了一個名為 hello 的公共方法。在 __name__ == "__main__" 的代碼塊中,我們使用 register.UseCommandLine 函數注冊了 COM 組件,并使用 win32com.server.register.UseCommandLine 函數創建了 COM 服務器。然后,我們使用 pythoncom.PumpMessages() 進入了消息循環,以等待客戶端調用 COM 組件的方法。
在實際使用中,你需要將代碼中的 {YOUR-CLSID} 替換為你的 COM 組件的 CLSID,可以使用 pythoncom.CreateGuid() 生成一個新的 CLSID。
請確保在運行代碼之前,已經安裝了 pywin32 庫和 Python for Windows 擴展(pywin32 依賴的組件)。
丸趣 TV 網 – 提供最優質的資源集合!
正文完