Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a command line program from within a C# application

I have written a C++ program (which executes from the command line), that works fine. Now I need to use it for my C# application. That is to say, I would like the output from my C++ program to be used in my C# application whenever it is called.

Is it possible? If so, how?

Any links or help would be appreciated.

like image 255
nightWatcher Avatar asked Dec 21 '22 18:12

nightWatcher


2 Answers

You can use System.Diagnostics.Process to fire up your C++ program and redirect its output to a stream for use in your C# application. The information in this question details the specifics:

string command = "arg1 arg2 arg3"; // command line args
string exec = "filename.exe";      // executable name
string retMessage = String.Empty;
ProcessStartInfo startInfo = new ProcessStartInfo();
Process p = new Process();

startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;

startInfo.UseShellExecute = false;
startInfo.Arguments = command;
startInfo.FileName = exec;

p.StartInfo = startInfo;
p.Start();

using (StreamReader output = p.StandardOutput)
{
    retMessage = output.ReadToEnd();
}

p.WaitForExit();

return retMessage;
like image 61
Andy Mikula Avatar answered Jan 06 '23 04:01

Andy Mikula


Make your C++ code DLL, and use pinvoke to call the C++ functions from C# code.

Read this article: Calling Win32 DLLs in C# with P/Invoke

Another way to do this is to use Process class from .Net. Using Process, you don't need to make your C++ code DLL; you can start your C++ EXE as a process from C# code.

like image 26
Nawaz Avatar answered Jan 06 '23 04:01

Nawaz