【发布时间】:2021-07-26 10:35:38
【问题描述】:
我想在 Fortran 程序和 C# 程序之间建立一个管道。 Fortran 程序将完成繁重的工作,而 C# 程序将提供正在完成的工作的“视图”(使用从 Fortran 程序发送给它的数据)。为了检查这是否可行,我编写了两个小程序。 (Fortran 代码是从 C++ 和 C# 之间的管道数据示例中窃取的。)
Fortran 代码:
PROGRAM Test
USE kernel32
IMPLICIT NONE
! Data pipe
INTEGER*4 EqnData /100/
! Paths for pipes
CHARACTER*128 dataname /'\\.\pipe\EqnData'/
INTEGER(HANDLE) :: pipe1
pipe1 = CreateNamedPipe('\\\\.\\pipe\\EqnData'C, PIPE_ACCESS_DUPLEX, &
PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, &
1024, 1024, 120 * 1000, NULL)
PRINT*, pipe1
! Open data pipe
OPEN(UNIT=EqnData, FILE=dataname, ACCESS='STREAM', STATUS='OLD')
READ*
! Close pipe
CLOSE(EqnData)
WRITE (*,*) 'end'
END
C#代码:
using System;
using System.IO;
using System.IO.Pipes;
class PipeClient
{
static void Main(string[] args)
{
using (NamedPipeClientStream pipeClient
= new NamedPipeClientStream(".",
"EqnData",
PipeDirection.InOut))
{
// Connect to the pipe or wait until the pipe is available.
Console.Write("Attempting to connect to pipe...");
pipeClient.Connect();
Console.WriteLine("Connected to pipe.");
Console.WriteLine("There are currently {0} pipe server instances open.",
pipeClient.NumberOfServerInstances);
using (StreamReader sr = new StreamReader(pipeClient))
{
// Display the read text to the console
string temp;
while ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("Received from server: {0}", temp);
}
}
}
Console.Write("Press Enter to continue...");
Console.ReadLine();
}
}
如果我同时启动这两个程序,我会看到 Fortran 代码创建了一个管道,并且它会到达 READ 语句,但 C# 代码只会到达 pipeClient.Connect(),然后就坐在那里。
我是否正确设置了 C# 方面?或者也许我在 Fortran 方面没有完全正确,以便 C# 客户端“看到”管道?
【问题讨论】:
-
不确定以 C 结尾的字符串。这在我使用的 Fortran 编译器上不起作用。尝试将 CreateNamedPipe 中的反斜杠数量减半。在读/写之前,您还需要一个 ConnectNamedPipe。至少其中一个程序应该正在编写。如果两者都在读,而没有人在写,那么什么都不会发生。
-
以下内容可能会有所帮助:csharpcodi.com/vs2/241/AutoHotkey.Interop/src/…
-
您使用的是哪个 Fortran 编译器?我无法让管道与打开/读/写一起工作。它们确实适用于原生 Windows 调用的 WriteFile 和 ReadFile。
-
我正在使用英特尔 Fortran。 @cup 的建议起到了作用。为其他人发布了下面的工作代码。