博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

Python调用C#编写的DLL

Posted on 2020-03-31 00:17  二灯大师  阅读(1188)  评论(0)    收藏  举报

起因是工作中需要用的开发编写的DLL,但是它是使用C#编写的,本人不想使用C#去写测试代码,所以需要使用Python来掉这个DLL内的方法

就用这个就很好,不要问为啥不用微软的Ironpython和别的啥,好用就行了,解决问题就可以了

一、安装

pip install pythonnet

网快的几秒钟就装好了

 

 二、直接上代码

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Python_CSharp
{
public class Class1
{
public int FindMax(int num1, int num2)
{
/* 局部变量声明 */
int result;

if (num1 > num2)
result = num1;
else
result = num2;

return result;
}
}
}

Python

# coding=utf-8
# clr是公共运行时环境,这个模块是与C#交互的核心
import clr
import sys

sys.path.append("E:\xxxxx") #加载DLL路径,所在的目录绝对路径也可以是相对路径
clr.FindAssembly('Yourname.dll') # 加载的dll文件名

from Yourname import * #导入命名空间,Yourname是你DLL的命名空间

instance = Class1() #实例化类
response = instance.FindMax(5, 6) #调用DLL里的方法
print(response)

 

 三、问题

如果遇到了name 'class' is not defined问题,检查dll和py运行目录的文件下是否有同名的东西比如DllName.exe,DllName.py等可执行程序