原文地址:http://blog.csdn.net/qqaiqqaiww/article/details/78202588
之前公司有套C# AES加解密方案,但是方案加密用的是Rijndael类,而非AES的四种模式(ECB、CBC、CFB、OFB,这四种用的是RijndaelManaged类),Python下Crypto库AES也只有这四种模式,进而Python下无法实现C# AES Rijndael类加密效果了。
类似于这种C# 能实现的功能而在Python下实现不了的,搜集资料有两种解决方案,第一种方式,使用IronPython 直接调用C# dll文件,教程网上很多,不在赘述了,这种方式有个缺点,用的是ironPython而非Python,只是集成了一些.net framework库的Python版本,更新维护少;第二种方式是,C# dll源码编译成Com组件,Python再调用COM组件Dll的方法。
网上有很多Python调用COM dll教程,但大部分是C或C++编写的dll,很少有比较全面的讲解COM组件生成至调用过程,下面结合自己摸索多天的经历,简单介绍下如何生成COM组件,以及用Python如何调用COM dll组件,分享给大家。
我也是小白 ……^ ^,高手请飘过,如有写的不对之处,还请多多包涵以指正...
1.如何生成C# COM组件
ComToPython类之前的[ClassInterface(ClassInterfaceType.None)]一定要有,否则Python调用时会报错。
[ProgId("ComToPython.Application")]指定Python调用COM时的名称,后面Python代码会看到。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Runtime.InteropServices;
- namespace ComToPython
- {
- [Guid("350779B9-8AB5-4951-83DA-4CBC4AD860F4")]
- public interface IMyClass
- {
- void Initialize();
- void Dispose();
- int Add(int x, int y);
- }
- [ClassInterface(ClassInterfaceType.None)]
- [Guid("16D9A0AD-66B3-4A8A-B6C4-67C9ED0F4BE4")]
- [ProgId("ComToPython.Application")]
- public class ComToPython: IMyClass
- {
- public void Initialize()
- {
- // nothing to do
- }
- public void Dispose()
- {
- // nothing to do
- }
- public int Add(int x, int y)
- {
- return x + y;
- }
- }
- }
GUID使用VS2010自带工具生成,工具--创建GUID,点击复制两个GUID分别放至两个类名之前
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- a=1
- b=2
- print "方法一:"
- from win32com.client import Dispatch
- dll = Dispatch("ComToPython.Application")
- result = dll.Add(a, b)
- print "a + b = " + str(result)
- print "方法二:"
- import comtypes.client
- dll = comtypes.client.CreateObject('ComToPython.Application')
- result = dll.Add(a, b)
- print "a + b = " + str(result)
运行代码,执行结果如下:
浙公网安备 33010602011771号