简体   繁体   中英

Include header file of another project into DLL project

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?

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 Enum XYZ 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM