什么是C和C#进程之间通信的最佳方式。 我需要从C#进程发送包含命令和参数等的消息。 到C过程。 然后C过程必须能够发送回复。
我在C#进程中启动了C进程。
实现这一目标的最佳方法是什么? 我尝试使用stdin和stdout,但这不能很好地工作(由于某种原因,C进程的stdin被一些字符串(x(U + 266C)Q)发送垃圾邮件(U + 266C是一个UTF8传送十六个音符 )
你真的需要单独的流程吗? 如果您拥有这两个代码,为什么不通过导入c库方法进行互操作调用:
class Program
{
[DllImport("yourlibrary.dll")]
public static extern int YourMethod(int parameter);
static void Main(string[] args)
{
Console.WriteLine(YourMethod(42));
}
}
并在您的C库中使用.def文件导出您的方法:
LIBRARY "yourlibrary"
EXPORTS
YourMethod
听起来你没有访问C程序源代码。 我会使用ProcessStartInfo来启动你的extern C程序。 但在此之前,您重定向输入/输出。 请参阅以下示例代码:
private void start()
{
Process p = new Process();
StreamWriter sw;
StreamReader sr;
StreamReader err;
ProcessStartInfo psI = new ProcessStartInfo("cmd");
psI.UseShellExecute = false;
psI.RedirectStandardInput = true;
psI.RedirectStandardOutput = true;
psI.RedirectStandardError = true;
psI.CreateNoWindow = true;
p.StartInfo = psI;
p.Start();
sw = p.StandardInput;
sr = p.StandardOutput;
sw.AutoFlush = true;
if (tbComm.Text != "")
sw.WriteLine(tbComm.Text);
else
//execute default command
sw.WriteLine("dir \\");
sw.Close();
textBox1.Text = sr.ReadToEnd();
textBox1.Text += err.ReadToEnd();
}
您的流程是需要并行运行还是启动外部流程并需要获取结果? 如果您刚刚启动子进程,那么,如注释中所述,您不会对传递给子应用程序的数据执行UTF16-> ASCII转换。
如果您需要并行运行进程并在它们之间交换消息,请查看我们专门为此类任务设计的MsgConnect产品。