环境
window10
conda
python=3.8
VS2013
.net4.5
C#库创建
创建项目
一定要选择类库,否则可能导致调用失败
设置命名空间
设置类名
创建2个成员函数,printx和add
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class TEST_CLS
{
public void printx()
{
Console.WriteLine("Hello world!!!");
}
public int add(int a, int b)
{
return a + b;
}
}
}
编译代码,生成dll文件如下:
ClassLibrary1.dll
python引用库
安装pythonnet
pip install pythonnet -i https://pypi.tuna.tsinghua.edu.cn/simple
库使用
import pythonnet
# 与其他模块不同此处不直接导入pythonnet 而是导入clr(python与c#交互核心)
import clr
# 为了方便理解这里给到dll所在的绝对路径且包含dll文件本身
dll_path = r'ClassLibrary1.dll'
clr.FindAssembly(dll_path)
#导入库
dll = clr.AddReference("ClassLibrary1")
#打印库信息,如果导入失败dll则为none
print(dll)
#从命名空间导入所有类,使用*导入所有
from ClassLibrary1 import *
# 实例化类
instance = TEST_CLS()
print(instance.add(22,5))
instance.printx()