LoadLibrary Problems. GetProcAddress return 0 always

Hello.
Ive been searching tutorials about how to read dll files and i came up with this:

// DLL
Main.h:
1
2
3
4
5
6
7
8
9
10
11
12

#ifndef _MAIN_H_
#define _MAIN_H_

#include <iostream>
#include <stdexcept>
#include <fstream>

_declspec(dllimport) void testfunc( int a );
 
#endif


Main.cpp
1
2
3
4
5
6
7
8
9
10
11

#include "main.h"
using namespace std;

#include <fstream>
#include "main.h"
 
__declspec(dllexport) void testfunc( int a )
{
    std::cout << "DLL Called! a:" << a << std::endl;
}


// App
Main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main(int argc, char** argv)
{
	HINSTANCE a = NULL;
	a = LoadLibrary(L"exampledll2.dll");
	static void (__cdecl *testfunc)(int) = NULL;
	if( a == NULL )
	{
		cout << "dll not found" << endl;
		system("Pause");
		return 0;
	}


	testfunc = (void(__cdecl *)(int))GetProcAddress((HMODULE)a, "testfunc");
	if( testfunc == NULL )
	{
		cout << "testfunc == NULL" << endl;
		system("Pause");
		return 0;
	}
	testfunc(120);
	FreeLibrary(a);
	return -100;
}

Out: testfunc == NULL
What went wrong here?
Use the decorated (mangled) name of the function.
http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B

Or disable C++ name decoration by giving it C (or __stdcall) linkage.

1
2
3
4
5
6
7
8
9
10
11
12
extern "C"
{
    _declspec(dllimport) void testfunc( int a );
}

extern "C"
{
    __declspec(dllexport) void testfunc( int a )
    {
        std::cout << "DLL Called! a:" << a << std::endl;
    }
}
tried both still same thing : /

Edit:

Now its working!
code:

DLL main.cpp
1
2
3
4
5
6
7
8
9
extern "C" __declspec(dllexport) bool GetWelcomeMessage(char *buf, int len)
{
    if(buf != NULL && len > 48)
    {
        strcpy(buf, "Welcome Message From My First DLL function\n");
        return true;
    }
    return false;
}


APP main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int main(int argc, char** argv)
{
	HINSTANCE a = NULL;
	typedef bool (*GW)(char *buf, int len);
	a = LoadLibrary(L"dllexample2");
	static void (__cdecl *testfunc)(int) = NULL;
	if( a == NULL )
	{
		cout << "dll not found" << endl;
		system("Pause");
		return 0;
	}


	GW GetWelcomeMessage = (GW)GetProcAddress(a, "GetWelcomeMessage");
	if( GetWelcomeMessage == NULL )
	{
		cout << "testfunc == NULL" << endl;
		system("Pause");
		return 0;
	}
	char buf[128];
    if(GetWelcomeMessage(buf, 128) == true) std::cout << buf;
	system("Pause");
	FreeLibrary(a);
	return -100;
}


I think the problem was that my dll project was win32 console app
but it should be Win32 project
This is the thing what i changed...
Last edited on
Topic archived. No new replies allowed.