在Python中调用C#的dll库_哔哩哔哩_bilibili
环境准备:
安装 pythonnet
pip install pythonnet
 
在Python中调用C#动态链接库(DLL),可以使用
pythonnet库,它允许直接使用 .NET 的程序集。以下是一个示例,展示如何使用pythonnet调用C#动态链接库中的方法。【pythonnet详解】—— Python 和 .NET 互操作的库-CSDN博客
注意事项
在pycharm中写import clr,若根据提示安装clr模块,在调用C#的dll动态连接库时会报错module 'clr' has no attribute 'AddReference' ·建议pip uninstall clr,安装pythonnet模块
module 'clr' has no attribute 'AddReference' · Issue #319 · r0x0r/pywebview · GitHub
C#中调用dll动态链接库
案例1:
在Python中调用C#的dll库_哔哩哔哩_bilibili
C# 代码

python 代码
 
案例2:
C#代码
假设有一个C#动态链接库
MyLibrary.dll,其中有一个类MyClass,包含一个方法MyMethod,该方法接收两个整数参数并返回它们的和。
// MyLibrary.cs
namespace MyLibrary
{
    public class MyClass
    {
        public int MyMethod(int a, int b)
        {
            return a + b;
        }
    }
}
 
Python代码
import clr  # 导入pythonnet
# 添加DLL引用
clr.AddReference(r'C:\path\to\MyLibrary.dll')
# 导入命名空间
from MyLibrary import MyClass
# 创建类的实例
my_instance = MyClass()
# 调用方法
result = my_instance.MyMethod(3, 5)
print(f"The result is: {result}")
 
C#中动态调用dll动态链接库的方法
需求:已知方法名称、参数个数和参数类型,在python中调用c#动态链接库
C#中与Python中类型的对应
在使用
pythonnet调用 C# 动态链接库中的方法时,Python 和 C# 的参数类型需要相互对应。以下是常见的类型映射:
 

- 对于复杂对象,确保已导入相应的命名空间(如
 System.Collections.Generic)。- 在 Python 中使用
 List,Dictionary等 C# 泛型类型时,需要指定类型参数。
案例1:
C#代码
假设有一个C#动态链接库
MyLibrary.dll,其中有一个类MyClass,包含一个方法MyMethod,该方法接收两个整数参数并返回它们的和。
// MyLibrary.cs
namespace MyLibrary
{
    public class MyClass
    {
        public int MyMethod(int a, int b)
        {
            return a + b;
        }
    }
}
 
Python代码
核心:获取非静态方法
- method = getattr(my_instance, method_name),利用getattr(par1,par2)方法
 //参数1为类的实例,参数2为方法名称
import clr
import System
# 添加DLL引用
clr.AddReference(r'C:\path\to\MyLibrary.dll')
# 导入命名空间
from MyLibrary import MyClass
# 创建类的实例
my_instance = MyClass()
# 动态调用方法
method_name = "MyMethod"
params = (3, 5)
# 获取方法
method = getattr(my_instance, method_name)
# 调用方法
result = method(*params)
print(f"The result is: {result}")
 
案例2:
C#代码:
假设有一个C#动态链接库
ClassLibrary1.dll,其中有一个类TestCsharp,包含一个静态方法方法test2()和一个非静态方法test1().
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
    public class TestCsharp
    {
        //private string name;
        //带参构造函数
        //public TestCsharp(string name) {
        //    this.name = name;
        //}
        // 无参构造函数
        public TestCsharp() { 
        }
        public int test1(int times) { 
            return times;
        }
        //静态方法
        public static int test2(int times) {
            Console.WriteLine(times);
            return times;
        }
        
    }
}
 
Python代码:
1.利用importlib和getattr()动态导入模块和类
- module_1 = importlib.import_module(namespace)//动态获取模块
 - class_1 = getattr(module_1, className)//动态获取类
 2.利用getattr()方法动态获取静态方法和非静态方法
- method1 = getattr(my_instance,methodName1)//非静态方法
 - method2 = getattr(class_1 ,methodName2)//静态方法
 
import os
import sys
import clr
import importlib
if __name__ == '__main__':
    dllName='ClassLibrary1.dll'
    namespace='ClassLibrary1'
    className='TestCsharp'
    methodName1='test1'
    methodName2 = 'test2'
    # paramsType=''
    paramsVal1=1
    paramsVal2 = 2
    #工作目录设置dll所在目录
    sys.path.append(os.getcwd())
    #找到c#程序集
    clr.FindAssembly(dllName)
    #设置命名空间参考【设置模块】
    dll=clr.AddReference(namespace)
    # print(dll)
    #从指定命名空间导入类
    # from ClassLibrary1 import TestCsharp
    module_1 = importlib.import_module(namespace)
    class_1 = getattr(module_1,  className)
    #实例化,非静态方法
    my_instance = class_1()
    # 获取方法
    method1 = getattr(my_instance,methodName1)
    #调用非静态方法
    print(method1(paramsVal1))
    method2 = getattr(class_1 ,methodName2)
    #调用静态方法
    print(method2(paramsVal2)) 
附加:
importlib是 Python 标准库中的一个模块,用于动态导入模块。它提供了一系列函数和类,允许你在运行时加载和操作模块。以下是
importlib的详细介绍,包括常见用法和示例。基本概念
importlib模块实现了import语句背后的导入机制。它提供了更为灵活和动态的方式来导入模块,允许你在运行时根据需要加载和操作模块,而不仅仅是在编译时或脚本开始时导入模块。使用
importlib.import_module()可以动态地导入模块。import importlib # 导入一个模块 module_name = 'math' math_module = importlib.import_module(module_name) # 使用导入的模块 result = math_module.sqrt(16) print(result) # 输出: 4.0
importlib是 Python 中强大且灵活的模块导入机制。它提供了动态导入、模块重载、自定义导入逻辑和其他高级功能,使得模块管理更加灵活和强大。通过理解和使用importlib,你可以更好地控制 Python 程序中的模块导入和管理。
getattr是 Python 的一个内置函数,用于从对象中获取属性值。它接受一个对象、属性名(字符串形式)和一个可选的默认值作为参数。如果指定的属性存在,则返回该属性的值;如果属性不存在且提供了默认值,则返回默认值;如果属性不存在且没有提供默认值,则引发
AttributeError异常。Python函数介绍:getattr函数的用法和示例-Python教程-PHP中文网
相关文章推荐:Java调用C++的DLL设计!!!解耦实用!!!-CSDN博客



















