我是C ++的新手。我的问题可能很愚蠢但是,任何帮助都会受到赞赏。
我有一个用C ++非托管代码编写的dll(我们没有这个dll的源代码),我尝试从C#P / Invoke调用但是,无法在控制台窗口中打印cout语句控制台应用。
出于绝望,我创建了一个C ++托管的dll包装器来调用前面提到的dll,然后在C#console app中引用了托管的dll,这也没有帮助。
我只能从C ++ win32 app打印cout语句。 非托管dll功能界面如下:
HRESULT WINAPI Foo(int len, LPCWSTR[] arg);
托管dll c ++ / cli正在使用上述功能,如下所示:
int Footool::FooMain(String ^ wargv, String ^ outFileName) {
wstring fileName = L"";
MarshalString(outFileName, fileName);
streambuf *psbuf, *backup;
ofstream filestr;
filestr.open(fileName);
backup = cout.rdbuf();
psbuf = filestr.rdbuf();
cout.rdbuf(psbuf);
cout << "Entering FooMain." << endl;
HINSTANCE fooDll = LoadLibrary(L"foo.dll");
if (fooDll == NULL) {
throw "foo.dll is not loaded.";
}
wstring args = L"";
MarshalString(wargv, args);
cout << args.c_str() << endl;
vector<wstring> arguments = split(args, ' ');
cout << "Size of the arguments: ";
for (wstring& s : arguments) {
cout << s.c_str() << endl;
}
LPCWSTR *lpcwstrArray = new LPCWSTR[arguments.size()];
for (int i = 0; i < arguments.size(); i++) {
lpcwstrArray[i] = arguments.at(i).c_str();
}
fooFunc sign = (fooFunc)GetProcAddress(fooDll, "Foo");
if (sign == NULL) {
throw "Could not load Foo method.";
}
cout << "Calling foo.dll." << endl;
HRESULT result = sign(arguments.size(), lpcwstrArray);
FreeLibrary(fooDll);
cout << "Exiting FooMain." << endl;
cout.rdbuf(backup);
filestr.close();
return (int)result;
}
C#P /调用尝试:
[DllImport("foo.dll", CharSet = CharSet.Auto, EntryPoint = "Foo", ExactSpelling = false,
CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int Foo
(
int argc,
string[] argv
);
呼叫者:
public static main()
{
string[] parameters = {"some", "Valid", "parameters"};
int returnResult = Foo(parameters.Length, parameters);
// try reading from console.
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.SetError(standardOutput);
}
有没有办法使用C#将cout语句打印到控制台?话虽如此,我在堆栈溢出上尝试了一些解决方案,提到了NamedPipe,AnonymousPipe等,它们也没有用。
由于