Python calls the C # Com dll component,

Source: Internet
Author: User
Tags custom name

Python calls the C # Com dll component,

Previously, the company had a set of C # AES encryption and decryption solutions, but the solution uses the Rijndael class for encryption, rather than the four AES models (ECB, CBC, CFB, OFB, these four types Use the RijndaelManaged class. In Python, the Crypto library AES only has these four modes. In this case, the C # AES Rijndael class encryption effect cannot be achieved in Python.

Similar to the functions that C # can implement but cannot implement in Python, there are two solutions to collect data. The first method is to use IronPython to directly call the C # dll file, there are a lot of tutorials online. I will not repeat them here. This method has a disadvantage. It uses ironPython instead of Python, but only integrates some. net framework library Python version, less update and maintenance; the second method is that C # dll source code is compiled into a Com component, Python then calls the COM component Dll method.

There are a lot of tutorials on calling COM dll using Python on the Internet, but most of them are dll written in C or C ++. There is little comprehensive explanation of the COM component generation and calling process, the following describes how to generate COM components and how to use Python to call the COM dll component based on your experience over the past several days.

I am also a little white ...... ^, Please let me know. If something wrong is written, please forgive me for correcting it...

1.How to generateC # COMComponents

Microsoft visual studio 2010 is used. First, create a project and select class library. The custom name is ComToPython. Then, click OK]

Rename the cs file: ComToPython. cs, which can be customized. Click Yes in the pop-up window]

Set COM visibility to True:

The above is equivalent to the following project property settings:

Check "register for COM interoperability ":

Create a new signature ComToPythonKey and deselect "use password to protect the key file"

Write the interface class IMyClass. The ComToPython class implements the three methods of the interface. For example, the Add () method is the function we want to implement and returns the sum of a and B.

[ClassInterface (ClassInterfaceType. None)] before the ComToPython class must be available; otherwise, an error will be reported during Python calling.

[ProgId ("ComToPython. Application")] specifies the name when Python calls COM. The Python code will see it later.

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 is generated using the built-in tool VS2010, tool -- create GUID, click Copy two guids to put them before the two class names

Note: Click Create GUID to copy the new GUID:

Finally, F6 compile and generate a solution. In your project Debug directory, ComToPython. dll is generated:

The last step is to register the COM component to the system.

Start Menu -- open the CMD command window (Administrator permission) in VS 2010 and navigate to the ComToPython. dll folder.

Run: gacutil/I ComToPython. dll to add dll to global Cache

Run regasmComToPython. dll to register the dll to the system.

2. PythonHow to callCOM dllComponents

I use Python 2.7, IDE uses PyCharm 2017.1, PyCharm new -- Project ComToPython, new project py file ComToPython. py

Set -- add two dependent libraries:

Add and install the pywin32 and comtypes dependency libraries, and use the following two methods to call the COM component:

After the dependency is installed, there will be a win32com folder under the Python installation directory site-packages. Double-click makepy. py under C: \ Python27 \ Lib \ site-packages \ win32com \ client \.

Select ComToPython and click OK.

Copy the COM component ComToPython. dll generated by VS2010 to the PyCharm ComToPython project folder:

Compile python to call COM dll code:

#! /Usr/bin/env python #-*-coding: UTF-8-*-a = 1b = 2 print "Method 1:" from win32com. client import Dispatchdll = Dispatch ("ComToPython. application ") result = dll. add (a, B) print "a + B =" + str (result) print "Method 2:" import comtypes. clientdll = comtypes. client. createObject ('comtopython. application ') result = dll. add (a, B) print "a + B =" + str (result)

Run the code. The execution result is as follows:

The above is the entire process of Python Calling C # COM Dll.

This practical tutorial on calling the C # Com dll component in Python is a small series to share with you all the content. I hope to give you a reference, and I hope you can provide more support for the customer's house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.