最近做一个.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);
}
}
