search
HomeBackend DevelopmentPython TutorialDetailed explanation of the process of calling C# Com dll component by Python

The following editor will bring you a practical tutorial on calling C# Com dll components from Python. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look.

Previously, the company had a C# AES encryption and decryption solution, but the solution encryption used the Rijndael class instead of the four modes of AES (ECB, CBC, CFB, OFB, this Four use the RijndaelManaged class), and the Crypto library AES under Python only has these four modes, and the C# AES Rijndael class encryption effect cannot be achieved under Python.

Similar to this kind of function that can be achieved in C# but cannot be achieved in Python, there are two solutions for collecting information. The first way is to use IronPython to directly call the C# dll file. There are many tutorials on the Internet, so I won’t go into details. Yes, this method has a disadvantage. It uses ironPython instead of Python. It only integrates some Python versions of the .net framework library, which requires less updates and maintenance. The second method is to compile the C# dll source code into a Com component, and then call it from Python. Methods of COM component Dll.

There are many Python tutorials on calling COM dlls on the Internet, but most of them are dlls written in C or C++. There are few comprehensive explanations of the COM component generation to calling process. The following is a simple summary based on my own experience of exploring for many days. Introduce how to generate COM components and how to call COM dll components using Python. Share them with everyone.

I am also a novice... ^ ^, masters, please pass by. If there is something wrong in what I wrote, please forgive me and correct me...

1 .How to generateC# COMComponent

I use Microsoft visual studio 2010, first create a new--project --Select [Class Library], customize the name: ComToPython, click [OK]

Rename the cs file: ComToPython.cs, which can be customized. In the pop-up window, select [Yes]

COM visibility is set to True:

The above is equivalent to the following project property settings :

Check "Register for COM interop":

Create a new signature ComToPythonKey and uncheck "Use Password-protected key file"

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

There must be [ClassInterface(ClassInterfaceType.None)] before the ComToPython class, otherwise an error will be reported when Python is called.

[ProgId("ComToPython.Application")] specifies the name when Python calls COM, which will be seen in the Python code 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 tool that comes with VS2010. Tool--Create GUID, click to copy the two GUIDs and place them before the two class names

Note: Click to create a new GUID to copy the newly created GUID:

Finally, F6 compiles and generates the solution, which is in the Debug directory of your project There will be ComToPython.dll generated:

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

Start menu--open the CMD command window that comes with VS 2010 (administrator Permissions) Locate to the ComToPython.dll folder

Execute: gacutil /i ComToPython.dll Add dll to the global cache

Execute: regasmComToPython.dll Register dll to the system

2.PythonHow to call COM dllComponent

I am using Python 2.7, PyCharm 2017.1 for IDE, PyCharm new - project ComToPython, new project py file ComToPython.py

Settings - add two dependent libraries:

Add and install pywin32 and comtypes dependency libraries to correspond to the latter two ways of calling COM components:

After the dependencies are installed, Python There will be a win32com folder in the installation directory site-packages directory. Double-click makepy.py

under C:\Python27\Lib\site-packages\win32com\client\. Select ComToPython and click OK

然后拷贝上面VS2010生成的COM组件ComToPython.dll至PyCharm ComToPython项目文件夹下:

编写python调用COM dll代码:


#!/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)

运行代码,执行结果如下:

以上就是Python调用C# COM Dll整个过程了

The above is the detailed content of Detailed explanation of the process of calling C# Com dll component by Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python's Execution Model: Compiled, Interpreted, or Both?Python's Execution Model: Compiled, Interpreted, or Both?May 10, 2025 am 12:04 AM

Pythonisbothcompiledandinterpreted.WhenyourunaPythonscript,itisfirstcompiledintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).Thishybridapproachallowsforplatform-independentcodebutcanbeslowerthannativemachinecodeexecution.

Is Python executed line by line?Is Python executed line by line?May 10, 2025 am 12:03 AM

Python is not strictly line-by-line execution, but is optimized and conditional execution based on the interpreter mechanism. The interpreter converts the code to bytecode, executed by the PVM, and may precompile constant expressions or optimize loops. Understanding these mechanisms helps optimize code and improve efficiency.

What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.