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類型資料