最近做一個.NETCore項目,需要調用以前用VB6寫的老程式,原本想重寫,但由於其調用了大量32DLL,重寫後還需要編譯為32位才能運行,於是乾脆把老代碼整個封裝為32DLL,然後準備在64位程式中調用。(註意Windows系統中,先要把DLL註冊為COM) 為了實現64位程式調用32DLL,我嘗 ...
最近做一個.NETCore項目,需要調用以前用VB6寫的老程式,原本想重寫,但由於其調用了大量32DLL,重寫後還需要編譯為32位才能運行,於是乾脆把老代碼整個封裝為32DLL,然後準備在64位程式中調用。(註意Windows系統中,先要把DLL註冊為COM)
為了實現64位程式調用32DLL,我嘗試了大量方法,但效果都不是很理想,偶然中發現.NetCore的“管道”,可以完美地解決這個問題,具體思路如下:
1、創建一個.NETFramework32位程式,在其中對封裝的老代碼進行引用(COM中引用),然後將其介面暴露
2、創建64位.NETCore程式,在其啟動時,為第一步創建的程式創建進程,並啟動
3、使用“雙工管道”讓64位程式與32程式進行通信,完美實現64位程式調用32DLL
下邊代碼展示一個簡單的管道通信過程:
A、64程式代碼
static void Main(string[] args) { //創建refpropPipe進程 Process process = new Process(); //將refpropPipe.exe放在與refprop64Hv相同路徑下,相對路徑引用 process.StartInfo.FileName = @"C:\Users\Administrator\source\repos\refpropPipe\refpropPipe\bin\Debug\refpropPipe.exe"; //process.StartInfo.FileName = "refpropPipe.exe"; process.Start(); double value = 0; //向refpropPipe發送調用信息,即查詢輸入變數值 using (NamedPipeClientStream pipeClientStream = new NamedPipeClientStream("request")) { pipeClientStream.Connect(); string input = Method + "," + FluidName + "," + InpCode + "," + Units + "," + Prop1 + "," + Prop2; using (StreamWriter writer = new StreamWriter(pipeClientStream)) { writer.WriteAsync(input); } } //接收refpropPipe返回的信息,即查詢結果 using (NamedPipeClientStream pipeClientStream = new NamedPipeClientStream("respose")) { pipeClientStream.Connect(); using (StreamReader reader = new StreamReader(pipeClientStream)) { string val = reader.ReadToEnd(); value = Convert.ToDouble(val); } } process.WaitForExit(); process.Close(); }
B、32位程式代碼
static void Main(string[] args) { double respose = 0; ///接收refprop64Hv的輸入信息 using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("request")) { pipeStream.WaitForConnection(); using (StreamReader reader = new StreamReader(pipeStream)) { //此處接收到消息後,對32Dll進行調用 } //向refprop64Hv返回結果 using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("respose")) { pipeStream.WaitForConnection(); using (StreamWriter writer = new StreamWriter(pipeStream)) { string res = respose.ToString(); writer.WriteAsync(res); } }