Home > database >  Extend C application (executable) with dynamically linked library code?
Extend C application (executable) with dynamically linked library code?

Time:03-28

I do not want to provide client with source code to an application (executable) but do want to allow the client to extend application functionality by modifying source written in a dynamically linked library.

The executable has a function called void handleGetResource(request, response) to handle incoming http requests.

handleGetResource is where the client's business logic resides. This is the C user code specific to the client.

I would like to compile this user code into a dynamic library so that I can provide the client only with the source code related to their business logic. This way, they can modify and rebuild this business logic without having access to my executable's source code.

Can someone provide me with some advice on how to best handle this? Both the app and the dynamic libraries would be written in C . Note: the executable is cross compiled to run on Win and Linux.

Thank you

CodePudding user response:

What you are describing is a plugin model where users or customers can provide their own compiled extensions to "handle" functionality on behalf of an application.

On Windows, you specify that customers build a DLL and export a function that matches your expected function signature. On Linux, you ask them to build a shared library (.so) - which is nearly the same thing as a DLL.

In your application, you will invoke LoadLibrary and GetProcAddress to load the customer's DLL from file and to get a function pointer to his implementation of handleGetResource:

 typedef void (*HANDLE_GET_RESOURCE)(Request* request, Response* response);
 HMODULE hMod = LoadLibrary("C:\\Path\\To\\Customers\\Dll\\TheirHandler.dll");
 HANDLE_GET_REQUEST handler = (HANDLE_GET_RESOURCE)GetProcAdderss(hMod, "handleGetResource");

Then to invoke:

 handler(&request, &response);

Then your customer can build a DLL with a definition like the following:

extern "C"  __declspec(dllexport) void handleGetResource(Request* req, Response* res)
{
   // their code goes here
}

You can do the same thing on Linux with dlopen and dlsym in place of LoadLibrary and GetProcAddress.

For windows, I would also be explicitly in having these typedefs and function defintions be explict with regards to __cdecl or __stdcall.

As to how the customer registers the full path to their compiled binary - that's a mechanism that you can decide for yourself. (e.g. command line, registry, expected file name in current directory, etc...)

  •  Tags:  
  • c
  • Related