1

I have DLL file which compiles in Delphi, functions export as __stdcall, and functions description txt file. I havn't got any source code.

And I'll use this DLL in visual studio c++ project. Google says that need use LoadLibrary + GetProcAddress , but GetProcAddress returns NULL if exported function declared as __stdcall, i.e. I can't call function with its name. And others recomended using .def file, but I don't know what .def file, and what need for generating .def file, if I can use this way on my situation, please describe thoroughly.

QA: How I can call these exported functions?

Here I post my main.cpp file, dll name and function name changed specially.

#include <Windows.h>
#include <tchar.h>
#include <cassert>
#include <cstdio>


int main()
{
    //foo(80, 127);
    HMODULE hLib;
    hLib = LoadLibrary( _T("MyDLL.dll") );

    assert(hLib != NULL ); // pass !!


    int ( __stdcall *pFoo)(int, int);
    (FARPROC &)pFoo = GetProcAddress(hLib, _T("foo") );

    if (pFoo== NULL )
    {
        DWORD errc = GetLastError();
        printf("%u\n",errc); // it gets error 127

    }else{
        printf("success load\n");
    }
//  pFoo(04,1);

    FreeLibrary(hLib);
    return 0 ;
}

1 Answer 1

4

First of all I suggest that you stop using tchar.h, _T, etc. That was useful when you needed to compile for Windows 98. But it's 2014 and surely you can forget that Windows 98 ever existed. So compile your applications for UNICODE and use L"..." for wide literals.

Of course, GetProcAddress only receives 8 bit text. So your current code is incorrect. You must not use _T("...") for the function name parameter of GetProcAddress. The documentation makes this clear.

Since your code compiles it must be that you are compiling for ANSI or MBCS. And if GetProcAddress returns NULL then clearly the DLL does not export a function with the name that you supply. Some possible reasons:

  1. You did not export the function.
  2. You exported the function but not by that name. Note that whilst Delphi is case insensitive, DLL functions importing/exporting is case sensitive. Perhaps you exported Foo rather than foo.

A trivial DLL that will work with the code in your question:

library MyDLL;

function foo(a, b: Integer): Integer; stdcall;
begin
  Result := a + b;
end;

exports
  foo;

end.

Note that .def files simple are not pertinent here. Delphi does not use .def files. And the calling convention cannot be relevant either. The name used by Delphi to export a function is not influenced by the calling convention.

Not the answer you're looking for? Browse other questions tagged or ask your own question.