PHP 类到 C# 类?

Lor*_*ron 5 php c#

我在一家使用 C# 制作应用程序的公司工作。最近,一位客户要求我们重建一个用 PHP 编写的应用程序。该应用程序从车载盒子接收 GPS 数据,并将其处理成可用的信息。

GPS 设备的制造商有一个 PHP 类,可以解析接收到的信息并提取坐标。我们正在考虑将 PHP 类重写为 C# 类,以便我们可以使用它并对其进行调整。来了,在制造商的网站上有一行文字让我毛骨悚然:

“传输数据的编码格式和内容会不断变化。这是由于新模块固件版本实现了附加功能而导致的,这使得您几乎不可能对其进行记录并自行正确解码。”

所以我现在正在寻找一个选项来使用“不断变化的”PHP 类并在 C# 中访问它。有些东西链接了一个外壳,只暴露了我需要的一些功能。但我不知道该怎么做。任何人都可以帮我找到解决方案吗?

Kaz*_*zar 3

我知道这是一个非常 hacky 的解决方案,但如果您需要一些 PHP 代码,并且不想每次都重复移植到 C#,您可以尝试以下方法,尽管这意味着您需要 php 命令目标机器上的直线工具。

第一步是有一个 php 脚本,它不断地从 stdin 读取数据,使用供应商提供的这个特殊类对其进行解码,并将结果写入 stdout。非常简单的例子:

<?php

include("VendorDecodingClass.php");

while(true) 
{
    $input = fgets(STDIN); //read off of the stdin stream

    //can't remember if this is valid, but somehow check that there is some data
    if($input) 
    {
         //pass it off to the vendor decoding class
         $output = VendorDecoding::decode($input);    

         fwrite(STDOUT, $output); //write the results back out
    }
    //sleep here so you don't suck up CPU like crazy 
    //(1 second may be a bit long tho, may want usleep)
    //Edit: From Tom Haigh, fgets will block, so the sleep isn't necessary
    //sleep(1); 
}

?>
Run Code Online (Sandbox Code Playgroud)

不管怎样,一旦你完成了这些,在你的 C# 应用程序中,在开始时创建一个新的 Process 来运行该脚本,然后将 Process 实例保存在某个地方,这样你就可以在以后引用 STDIN 和 STDOUT。例子:

ProcessStartInfo procStartInfo = new ProcessStartInfo("php", "yourscript.php");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;

Process proc = new Process(); //store this variable somewhere
proc.StartInfo = procStartInfo;
proc.Start();
Run Code Online (Sandbox Code Playgroud)

然后,当您想要解码数据时,只需写入您创建的 php 进程的标准输入,然后等待标准输出上的响应。使用 stdin/stdout 方法比每次想要解码某些数据时创建一个新进程要高效得多,因为创建该进程的开销可能会很明显。

proc.StandardInput.WriteLine(somedata); //somedata is whatever you want to decode

//may need to wait here, or perhaps catch an exception on the next line?

String result = proc.StandardOutput.ReadLine();

//now result should contain the result of the decoding process
Run Code Online (Sandbox Code Playgroud)

此处免责声明,我尚未测试任何代码,但这就是我如何做到这一点的一般要点。

我刚刚想到的其他事情是,您需要某种机制来终止 PHP 进程。使用 可能没问题Process.Kill,但如果解码执行任何文件 IO,或任何关键的操作,您可能希望以某种方式向 php 脚本发送中断信号。