Exporting from dll - Why do I need "extern C"?
Hi,
I was trying to call an exported function in a dll from my application
but was getting "ERROR_PROC_NOT_FOUND" (from GetLastError) when I
called GetProcAddress to retrieve a pointer to the exported function.
Below is the relevant code...
<code>
// In the dll ---------
__declspec (dllexport) CString getString()
{
return CString("abc");
}
// In the exe ---------
void test (void)
{
CString (*dllFn)(void); // function pointer for the dll
function.
// LoadLibrary here... which is successful
dllFn = (CString(*)(void)) ::GetProcAddress(hDll, "getString");
// at this point dllFn is NULL and GetLastError
// returns 127 = ERROR_PROC_NOT_FOUND
// FreeLibrary here... which is also successful
}
</code>
This is a cutdown snippet,,, just to highlight the problem.
The dll loaded successfully but it couldn't find the exported
function. After spending some time with MSDN, I went to google... and
to make the story short... I found out that adding extern "C" before
__declspec (dllexport) in the dll made the thing work fine (although,
I get a warning about returning a CString from the function because
its incompatible with C).
Now the question is, why do I have to do this? What is the
significance of this extern "C" and is it a safe/usual practice to use
it?
I did check out MSDN but the exporting methods described there don't
say anything about using it.
Would someone care to explain why the code works with this?
I'm on VS2005...
TIA
Adeel