起因是工作中需要用的開發編寫的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等可執行程序