Python中调用C#的dll库

Python中调用C#的dll库

1、创建C#的dll库。dll名称为MyCsharpDLL.dll,下面是dll里面的代码

using System;
 
namespace MyCsharpDLL
{
    public class Test
    {
        public void Print()
        {
            Console.WriteLine("Hello world!!!");
        }
 
        public void Print(string msg)
        {
            Console.WriteLine($"Hello {msg}!!!");
        }
 
        public double Add(double x, double y)
        {
            return x + y;
        }
    }
}

2、通过在Python中调用clr(pythonnet中工具)来对C#的dll库进行加载使用,下面是Python调用C#里面方法的代码

import os
import clr
import sys
sys.path.append(os.getcwd())
 
# 读取DLL文件
clr.FindAssembly("MyCsharpDLL.dll")
dll = clr.AddReference("MyCsharpDLL")
 
print(dll)
 
from MyCsharpDLL import *
 
def print_hi(name):
    # 实例化类
    instance = Test()
    # 无输入及无返回
    instance.Print()
    # 有输入及无返回
    instance.Print("lqwvje")
    # 有输入及输出
    add_data = instance.Add(1, 1)
    print(add_data)
 
# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    print_hi('PyCharm')
posted @ 2024-04-15 14:29  冀未然  阅读(1511)  评论(0)    收藏  举报