软件+环境:VS、C#、pycharm、python3.8
一、利用VS 编写 dll
1、新建项目,请把名称写的容易识别一点
2、代码如下,大致就包含两个函数,一个返回 一列字符串,一个返回 根据参数做加法
C# 完整代码如下
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace dlltest{public class Class1{public string _doc_(){return "dlltest 是一个C#的DLL动态链接库";}public int add (int a, int b){return a + b;}}}
3、点击 菜单栏->重新生成解决方案
此时 输出栏 我们可以看到有个dll文件路径,所以你懂的,我们已经做出了个简单的dll文件
接下来的任务就是如何使用 python调用dll
二、python 调用 dll
python 调用dll 常见有两个库(ctypes[系统自带]、clr)。
ctypes一般在C++的dll中使用、C#我们使用clr。
安装:pip installpythonnet 或者 使用 pycharm库安装
import clr # C## dll路径path = r'd:\microsoft visual studio \Projects\dlltest\dlltest\bin\Debug\dlltest.dll'# 加载dll# clr.FindAssembly(path) 由于作者使用python 3.8 该方法表示已经弃用,故采取下列方法clr.AddReference(path)# 导入 命名空间内 所有的 Classfrom dlltest import *# 实例化对象TestClass = Class1()# 使用dll中的方法print(TestClass._doc_())print("1+2={}".format(TestClass.add(1, 2)))
python控制台 output:
dlltest 是一个C#的 DLL动态链接库
3
三、报错
1、如果 调用的是C#生成的dll,请使用clr库
2、clr 模块不存在、或者AddReference方法不存在
请安装 pythonnet
3、python 编译器发现代码部分 飘红,请不用在意,这是由于pycharm不知道这个dll里面到底有什么方法,不影响程序运行,我们在看有些程序自带库的时候偶尔也有这情况。