win64 DLL stdout printing after main process completes

Mike Parker aldacron at gmail.com
Tue Apr 20 07:07:31 UTC 2021


On Monday, 19 April 2021 at 14:55:03 UTC, cc wrote:

> I would expect the first three lines of dll output to precede 
> the "[Main] x:" line at least.  Is there something I'm doing 
> wrong?  Do I need to somehow pass a reference to the main stdio 
> to the DLL's D runtime similar to how the GC can be shared?

I just compiled and executed your code locally here's the output 
I saw without using any flushing:

```
[dll] DLL_PROCESS_ATTACH
[dll] static this for mydll
[Main] Start
[dll] MyDLL_Test
[Main] x: 5
[Main] Finished
[Main] END
[dll] DLL_PROCESS_DETACH
[dll] static ~this for mydll
```

My command lines:

```
dmd -m64 -L/DLL mydll.d
dmd -m64 main.d
```

I dropped the -of because that's redundant. The .def file isn't 
needed, but I did compile with one based on the example you 
linked. It gave me warnings about all of the directives being 
ignored because they're unsupported on the target platform (I 
also had to change MyDLL_Test to extern(C), since I didn't use 
the D mangled name in the .def file) but the output was the same 
as above.

I did have a problem, though, when I replaced printf with 
writeln/writefln, in that I got no output at all. I don't have 
time to dig deeper at the moment.

Anway, I wonder what the difference is between our systems that 
we get different output. I'm on Windows 10, dmd 2.096.0, VS 2019.

I suggest you also try compiling a comparable C example to see if 
what the output looks like:

```c
// dllmain.c
#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>

BOOL DllMain(HINSTANCE hinst, ULONG reason, LPVOID reserved)
{
     switch(reason)
     {
         case DLL_PROCESS_ATTACH:
             printf("[dll] DLL_PROCESS_ATTACH\n");
             break;

         case DLL_PROCESS_DETACH:
             printf("[dll] DLL_PROCESS_DETACH\n");
             break;

         case DLL_THREAD_ATTACH:
             printf("[dll] DLL_THREAD_ATTACH\n");
             return 0;

         case DLL_THREAD_DETACH:
             printf("[dll] DLL_THREAD_DETACH\n");
             return 0;

         default: break;
     }

     return 1;
}

__declspec(dllexport) int __cdecl MyDLL_Test(void)
{
     printf("[dll] MyDLL_Test\n");
	return 5;
}
```

```c
// main.c
#include <stdio.h>

#pragma comment(lib, "dllmain.lib")

extern __declspec(dllimport) int __cdecl MyDLL_Test(void);

int main(int argc, char** argv)
{
     printf("[Main] Start\n");
     int x = MyDLL_Test();
     printf("[Main] x: %d\n", x);
     printf("[Main] Finished\n", x);
     printf("[Main] END\n");
}
```

In the *x64 Native Tools Command Prompt for VS 2019*:

```
cl /LD dllmain.c
cl main.c
```

See if this produces the output you expect or if it looks the 
same as your D output.







More information about the Digitalmars-d-learn mailing list