0

I have created a test application which uses DLL file and call its internal function(s).

I followed the steps given in the link: Dynamically load a function from a DLL

I have Win32 console application and a DLL creator application. Ideally the Win32 application LoadLibrary() and GetsProcAddress() and get the function pointer for that particular function inside the DLL with parameters passed, returns results, all done working fine.

Now, what I need to do is, From console application I need to call a function inside DLL and in DLL function I need to call a function in Win32 console application to get the values instead of passed as a parameter.

Something like this,

1) Include the same header file used in Win32 console project into the DLL project. 2) When the function inside the DLL project called by Win32 console project 3) Get value from console project, process it and set value back to the console application

dllmain.cpp:

#include "evaluate.h"

extern "C" __declspec(dllexport) int _cdecl ADD(void)
{
    int a = getValueOfA();
    int b = getValueofB();
    setValueOfC((a+b));
}

evaluate.cpp:

int getValueOfA(void)
{
    return 3;
}

int getValueOfB(void)
{
    return 5;
}

void setValueOfC(int c)
{
    printf("\nValue of C is: %d",c);
}

HINSTANCE hGetProcIDDLL;
typedef int(_cdecl *func_ptr)();
hGetProcIDDLL = LoadLibrary("MyDll.dll);
func_ptr addFunc = (func_ptr)GetProcAddress(hGetProcIDDLL, "ADD");
addFunc();

evaluate.h

int getValueOfA();
int getValueOfB();
void setValueOfC(int value);

MyDll.def:

EXPORTS
    ADD   @1

Any additional code or procedure need to be followed? Is this doable?

Community
  • 1
  • 1
kar
  • 495
  • 1
  • 8
  • 19
  • Is that your actual code? Do you really have statements outside of any function? Please try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us. – Some programmer dude May 15 '15 at 20:54

1 Answers1

0

While it is possible for a DLL to import symbols exported by the main application, it is quite complicated.

A much simpler (easier to debug and therefore "better") approach is to pass a function pointer to the DLL, through which it can call back to the application function.

This can be done as a function parameter of function pointer type, passed to the function that will use it. Or it can be configured long in advance and saved in a global variable within the DLL, and the function which needs it retrieves this global variable and uses it for an indirect call.

You can see examples of callback function pointers throughout the Windows API -- virtually any API function named EnumXYZ accepts a callback. An example of saving a function pointer for later use would be a window procedure, which is stored by RegisterClass and then used during message processing SendMessage, GetMessage, DispatchMessage, etc.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720