- 1 year ago
Sending messages from C++ windows desktop app to DLL
Comment
1 / 1
To send messages from a C++ Windows desktop application to a DLL, you can use function pointers or callbacks.
- Define a function pointer in your DLL that will serve as the entry point for receiving messages from the desktop application. For example:
cpp// DLL header file
typedef void (*MessageCallback)(const char* message);
// Declare a callback function pointer
extern "C" __declspec(dllexport) void RegisterMessageCallback(MessageCallback callback);
- Implement the function in your DLL to store the provided callback function pointer. This allows the DLL to call the registered callback when it needs to send a message to the desktop application.
cpp// DLL source file
static MessageCallback s_MessageCallback = nullptr;
// Register the callback function
extern "C" __declspec(dllexport) void RegisterMessageCallback(MessageCallback callback)
{
s_MessageCallback = callback;
}
// Call the registered callback to send a message
void SendMessageToDesktopApp(const char* message)
{
if (s_MessageCallback)
{
s_MessageCallback(message);
}
}
- In your C++ Windows desktop application, load the DLL using
LoadLibrary
and retrieve the function pointer forRegisterMessageCallback
. Call this function to register a callback function from your desktop application.
cpp// Windows desktop application
typedef void (*MessageCallback)(const char* message);
// Load the DLL
HMODULE dllHandle = LoadLibrary(L"your_dll.dll");
if (dllHandle)
{
// Get the function pointer for RegisterMessageCallback
MessageCallback registerCallback = reinterpret_cast<MessageCallback>(GetProcAddress(dllHandle, "RegisterMessageCallback"));
if (registerCallback)
{
// Define your callback function to receive messages from the DLL
void MyCallback(const char* message)
{
// Handle the received message
// ...
}
// Register your callback function with the DLL
registerCallback(&MyCallback);
}
}
// Use SendMessageToDesktopApp function in your code to send messages to the DLL
By using this approach, you can establish communication between your C++ Windows desktop application and the DLL, allowing the DLL to receive messages from the application and respond accordingly.