簡體   English   中英

如何在C和C#應用程序之間進行通信

[英]How to communicate between a C and a C# application

什么是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產品。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM