First, all the code in the DLL can be in C++
except the functions you call from your program.
A DLL is an old C whiz-bang where you use the name of the DLL funcrtion in your program:
- FARPROC ptr = GetProcAddress(hModule, "AreaOfSquare");
Unfortunately, AreaOfSquare is never found in the DLL. The C++ compiler has mangled the name in the DLL. Therfore, the function in the DLL must be extern "C":
- //In the DLL:
-
extern "C"
-
int __stdcall AreaOfSquare(int len, int wid)
-
{
-
ACplusplusFunction();
-
}
The ACplusplus function does not need to be extern "C" since it is never called using a literal "ACplusplus".
So, your DLL interface must be designed correctly.
The extern "C" can be avoided by using a DEF file to export the mangled name as an alias:
- ;BEGIN ADLL.DEF FILE
-
;This DEF file is required becuase the argument to GetProcAddress()
-
;for the function is a C-string and it will never be equal to the
-
;C++ mangled name for the function
-
;This DEF file maps the mangled name to a name that can be used with GetProcAddress()
-
;Note also: Change project settings in Visual Studio to send the LINK this def file.
-
;Visual Studio.NET: Project Properties/Linker/Input/Module Definition File/...Path to the def file\Adll.def
-
LIBRARY ADll
-
EXPORTS
-
;Exported Name C++ Mangled Name
-
AreaOfSquare = ?AreaOfSquare@@YGHHH@Z
-
DisplayFromDll = ?DisplayFromDll@@YGXXZ
-
;END DEF
FILE
Lastly, the DLL export functions must use the __stdcall convention (WINAPI).
If you use GetProcAddress and you are successful in getting a non-null FARPROC returned, I would typecast that pointer into a function pointer of the correct type. That way when I call the DLL function inside my program, I can just use the name that was coded inthe DLL in the first place:
- FARPROC ptr = GetProcAddress(hModule, "AreaOfSquare");
-
int (__stdcall *AreaOfSquare)(int, int);
-
//Type-cast the address returned from GetProcAddress to the function pointer type
-
AreaOfSquare = reinterpret_cast<int (__stdcall*)(int,int)> (addr);
-
cout << "The area of a 6x8 square is " << AreaOfSquare(6,8) << endl;
-