3

I was searching through stackoverflow questions but none of them answered my question. I have a game engine and I want to load player AI (written in c++) in runtime.

  1. Click on button, file dialog appears
  2. Choose file with AI (.dll or something?)
  3. Click on 'start' button, game starts using AI's that I add.

AI could be a method or whole class, it doesn't matter. I think I should generate .dll but I not sure how to do that. This class should look like this:

class PlayerAI
{
    void computeSomething(list of argument, Object& output)
    {
        // some logic
    }
}
Isaac
  • 115
  • 10

2 Answers2

3

Since you mention already compiled DLLs, you want to look at LoadLibrary and GetProcAddress. That's how you do runtime loads of DLLs and extract specific functions from them.

Examples can be found under Using Run-Time Dynamic Linking.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Note: DLL exports don't usually play nice with C++ classes. You'll probably want to use a C compatible interface (that can use C++ classes under the hood if needed); C++'s name mangling and ABI is just not well suited to this use case. – ShadowRanger Oct 06 '15 at 14:12
  • If the question were flagged "Windows" in any way, this would be a sure upvote. [This question / answer](http://stackoverflow.com/a/24089878/60281) handles the POSIX part of the computing world. – DevSolar Oct 06 '15 at 14:18
  • 2
    @DevSolar You mean in addition to the note ".dll or something" in the question? – Angew is no longer proud of SO Oct 06 '15 at 14:22
  • @Angew: In Linux: `echo "int main() {}" > somefile.dll` Whoops! You can name files anything. :P – Lightness Races in Orbit Oct 06 '15 at 14:39
  • @Angew: I don't base assumptions on statements that include "or something". ;-) Besides, there's always the future visitor to consider, who will come here based on the question title most likely. ;-) – DevSolar Oct 07 '15 at 07:38
3

Assuming pure Windows platform since none specified -

If you want to inject DLL, first obtain a handle to it using LoadLibrary-function like so:

HINSTANCE handleLib; 
handleLib = LoadLibrary(TEXT("YourDLL.dll")); 

You may then obtain a function pointer to a specific function in the lib. Like this:

FUNC_PTR func;
func = (FUNC_PTR) GetProcAddress(handleLib, "yourFunc");

Then you can call the function like so:

 (func) (L"TESTSTRING HERE"); 

When done, call FreeLibrary(libhandle)

How to declare a function as exported is in VS for instance like this (this is needed to mark your function in your DLL that you precompile:

__declspec(dllexport) int __cdecl yourFunc(LPWSTR someString)
{
   //Code here... 
}
Richard Tyregrim
  • 582
  • 2
  • 12