Answer the question
In order to leave comments, you need to log in
Get in .NET string from C++ dll
SW. specialists need help, two weeks are thrown out of life, so
there is a dll written in C ++ with very simple content.
Question, how to call this function in .NET and get the result of its work?
The question is not as simple as it seems, if you do return("bla bla bla") in C ++, then everything works fine, as soon as stdout appears, then nightmares begin.
As a result of digging the network through Google, I found almost what I needed , they work as it should, but !!! works once, when you call it again, it will hang ...
Thank you in advance for your help.
void IsolatedFunction()
{
cout << "Redirected string1" << endl << "Redirected string2" << endl;
}
Answer the question
In order to leave comments, you need to log in
Try not to create an instance of AnonymousPipeServerStream several times, but create it once and call SetStdHandle once, then calling server.Flush();, then the function from the dll and reading from the pipe. In general, something like this (I did not check the performance):
Copy Source | Copy HTML
- public static class ConsoleOutRedirector
- {
- #region Constants
-
- private const Int32 STD_OUTPUT_HANDLE = -11;
-
- #endregion
-
- #region Externals
-
- [DllImport("Kernel32.dll")]
- extern static Boolean SetStdHandle(Int32 nStdHandle, SafeHandleZeroOrMinusOneIsInvalid handle);
- [DllImport("Kernel32.dll")]
- extern static SafeFileHandle GetStdHandle(Int32 nStdHandle);
-
- #endregion
-
- #region Variables
-
- private static AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out);
- private static client = new AnonymousPipeClientStream(PipeDirection.In, server.ClientSafePipeHandle);
- private static bool First = true;
-
- #endregion
-
- #region Methods
-
- public static String GetOutput(Action action)
- {
- Debug.Assert(action != null);
-
- using (server)
- {
- if (First)
- {
- var defaultHandle = GetStdHandle(STD_OUTPUT_HANDLE);
-
- Debug.Assert(!defaultHandle.IsInvalid);
- Debug.Assert(SetStdHandle(STD_OUTPUT_HANDLE, server.SafePipeHandle));
- try
- {
- action();
- }
- finally
- {
- Debug.Assert(SetStdHandle(STD_OUTPUT_HANDLE, defaultHandle));
- }
-
- First = false;
- }
-
- server.Flush();
- client.Flush();
-
- using (client)
- {
- using (var reader = new StreamReader(client))
- {
- using (var writer = new StringWriter())
- {
- while (reader.Peek() != -1)
- {
- writer.Write(Convert.ToChar(reader.Read()));
- }
- return writer.ToString();
- }
- }
- }
- }
- }
-
- #endregion
- }
-
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question