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 @   冀未然  阅读(1154)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示