Tuesday, February 10, 2009

A problem of forward declaration in C++/CLI

Today while I started debugging my program, the programmed stopped at
Assembly assembly=Assembly.Load(name)
foreach(Type type in assembly.GetTypes()
{
...
}
and the output window showed:
First-chance exception at 0x7c81eb33 (kernel32.dll) in myprogramm.exe: Microsoft C++ exception: EETypeLoadException at memory location 0x0012d324..
First-chance exception at 0x7c81eb33 (kernel32.dll) in myprogramm.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000..
A first chance exception of type 'System.Reflection.ReflectionTypeLoadException' occurred in mscorlib.dll
Later I found that all these happens due to a unresolved forward declaration of a ref class. but the unresolved native class will not cause the problem.

So be caution when you are using the forward declaration for a ref class.

Tuesday, January 13, 2009

Create console for nonconsole application.

First we need to create a console:
BOOL result=AllocConsole();
assert(result);
Then we need to get the handle to the console, and associate the console to the standard output stream:
HANDLE hOutput=CreateFile(L"CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
SetStdHandle(STD_OUTPUT_HANDLE,hOutput);
In CRT, we also need make the stdout usable:
#include
#include
int hCrt=_open_osfhandle((intptr_t)hOutput,_O_TEXT);
FILE* hf=_fdopen(hCrt,"w");
*stdout=*hf
If in C++/CLI, We also need to replace System::Console::Out:
ref class __ConsoleWriter : public TextWriter
{
private:
HANDLE handle;
__ConsoleWriter(HANDLE handle):handle(handle){}
public:
virtual property System::Text::Encoding^ Encoding
{
System::Text::Encoding^ get()override
{
return System::Text::Encoding::UTF8;
}
}
virtual void Write(array^ buffer, int index, int count)override
{
array^ bytes=Encoding->GetBytes(buffer, index, count);
pin_ptr p=&bytes[0];
DWORD n;
WriteFile(handle, (LPVOID)p, bytes->Length, &n, NULL);
}
};
//Redirect the CLR output
Console::SetOut(gcnew __ConsoleWriter(hOutput));

That's it, quite simple.