Python真的是非常强大的胶水语言,可以与其他语言无缝衔接,之前做的项目是使用Pyqt5与C#结合编程,这里记录下Python调用C#的dll公共库的方法。
一、安装
想要使用C#生成的dll公共库则需要安装对应的调用包,直接使用安装命令pip install pythonnet
安装对应的包即可愉快的调用了
二、封装与初始化
最好是将调用模块封装为一个类,并可以改为单例模式,方便一次实例化后全局调用。导入包最好使用动态导入方式,可以避免Pycharm报错找不到相关的包,动态导入使用__import__
@singleton
class DataBaseDll(object):
__first_init = False
def __init__(self, str:dll_path)
import clr
sys.path.append(dll_path) # dll_path指dll入口文件所在路径
clr.FindAssemble("DataInterface.dll")
clr.AddReference("DataInterface")
DataInterface = __import__("DataInterface", fromlist=["RelationInterface", "AirModelManager"])
System = __import__("System", fromlist=["NullReferenceException", "Collections"])
self.SimulationInterface = DataInterface.RelationInterface.SimulationInterface()
self.AirModel = DataInterface.AirModelManager.AirModel()
self.__first_init = True
def test_static_task(self, str:task_id):
return self.SimulationInterface.TestStaticTask(task_id)
其中的C#的DataInterface.cs文件是这样的
namespace DataInterface.RelationInterface
{
public class SimulationInterface
{
public static List<StaticTask> TestStaticTask(string taskId);
三、调用
先实例化这个类,然后直接调用方法即可
dll_obj = DataBaseDll()
data_list = dll_obj.test_static_task("1d3hjh56hll7jk8kj9k9kj6jh5ll") # 此处返回的是python的list类型数据