views:

111

answers:

3

What would be the best way to communicate between a C and a C# process. I need to send messages containing commands and params and such from the C# process. to the C process. and the C process then has to be able to send reply's.

I start the C process in the C# process.

What would be the best way to achieve this? I tried using stdin and stdout but this doesn't work well (for some reason the stdin of the C process is spammed with some string (x(U+266C)Q) (U+266C is a UTF8 beamed sixteen note)

+4  A: 

Do you really need as separate processes? If you own both codes why don't you make interop calls by importing the c library methods:

class Program
{
    [DllImport("yourlibrary.dll")]
    public static extern int YourMethod(int parameter);

    static void Main(string[] args)
    {
        Console.WriteLine(YourMethod(42));
    }
}

and in your C library you export your method using a .def file:

LIBRARY "yourlibrary"
  EXPORTS
     YourMethod
jmservera
In the end it turned out that we could just use the library that the C code was using in C#. Thanks!
Pim Jager
A: 

Do your processes need to run in parallel or you start an external process and need to obtain it's results? If you just start a child process, then, as said in the comment, you don't perform UTF16->ASCII conversion of data being passed to the child application.

If you need to run processes in parallel and exchange messages between them, take a look at our MsgConnect product, which was designed specifically for such tasks.

Eugene Mayevski 'EldoS Corp
+1  A: 

It sound like you dont have access to the C program source code. I would use ProcessStartInfo to launch your extern C program. But before you do, you redirect the Input/Output. See sample code below:

    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();
}
Black Frog
Thanks. As it turned out we could just ignore the C program completely and use the library used in the C program. But thanks for your answer, it was very helpfull.
Pim Jager