As @cyanfish mentioned in comment section, "it's vital that the bottom CYGTLS_PADSIZE bytes of the stack are not in use before you call cygwin_dll_init()". I have tried to reserve those bytes via stackalloc
and it seems to work.
IntPtr pcygwin = LoadLibrary("cygwin1.dll");
IntPtr pcyginit = GetProcAddress(pcygwin, "cygwin_dll_init");
Action init = (Action)Marshal.GetDelegateForFunctionPointer(pcyginit, typeof(Action));
var thread = new Thread(() => {
unsafe {
var bytes = stackalloc char[8096];
init();
// Now I can freely call functions from cygwin1.dll
}
}, Int.MaxValue);
thread.Start();