Python调用C#dll动态链接库

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类型数据
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值