getProcAddress - NULL is returned
Asked Answered
B

2

6

I have the following code:

  //mydll.cpp
    #include <Windows.h>
    #include <io.h>

    #define STDOUT_FILEDESC 1

    class MYSTDOUT {
        bool shouldClose;
        bool isBuffered;
    public:
        MYSTDOUT(bool buf = true, bool cl = true) 
            : isBuffered(buf),
              shouldClose(cl) 
        {}
        ~MYSTDOUT() {
            if (shouldClose) {
                close(STDOUT_FILEDESC);
            }
        }
    };

    __declspec(dllexport) void* mydll_init_stdout()
    {
        static MYSTDOUT outs;
        return &outs;
    }
//test_dll.cpp
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <io.h>


typedef void* (__cdecl *MYPROC)(void);


int main(void)
{
  int fd;
  void *pstdout;

  MYPROC init_stdout;
  HMODULE handle = LoadLibrary(TEXT("mydll.dll")); 

  init_stdout = (MYPROC)GetProcAddress(handle,"mydll_init_stdout");//NULL

  FreeLibrary((HMODULE) handle);
  return 0;
}

I get that init_stdout is NULL.What could be a problem? handle is OK(Not NULL) Thank you

Bula answered 20/4, 2012 at 16:51 Comment(0)
G
15

That is due to name-mangling.

You need to wrap the exported function in extern "C" as:

extern "C"
{
    __declspec(dllexport) void* mydll_init_stdout()
    {
        static MYSTDOUT outs;
        return &outs;
    }
}
Grantee answered 20/4, 2012 at 16:53 Comment(1)
Damn... I'm too old for this. It's been 24 years since I last used it. Thanks.Shafting
S
11

Have a check in Dependency Walker, or dumpbin /exports and you will see that mydll_init_stdout has been exported with a mangled C++ name. That's why the GetProcAddress call fails.

Use extern "C" to stop mangling.

extern "C" 
{
    __declspec(dllexport) void* mydll_init_stdout()
    {
        static MYSTDOUT outs;
        return &outs;
    }
}
Sporangium answered 20/4, 2012 at 16:52 Comment(1)
thanks.. dumpbin also helps. These were the days of COM and IUnknown.Shafting

© 2022 - 2024 — McMap. All rights reserved.