How to load the DLL from the main project c++ -
i have created project uses 2 dll's play against each other (a dll player). game first player picks number , second player picks number, , playround function compares 2 numbers. problem not sure how load dll (run/load time). created first dll (simple.dll) has pick function returns "int 2" simplicity:
#include "stdafx.h" #define asexport #include <iostream> #include "player.h" using namespace std; int pick(int round, int mymoves[], int opponentmoves[]) { return 2; }
this project have header (player.h) following code:
#ifndef asexport #define dllimportorexport dllimport #else #define dllimportorexport dllexport #endif _declspec(dllimportorexport) int pick(int round, int mymoves[], int opponentmoves[]);
not sure include code include in main or in function:
hinstance hinstlib; myproc procadd; bool ffreeresult, fruntimelinksuccess = false; // handle dll module. //hinstlib = loadlibrary(text(player2name)); hinstlib = loadlibrary(); // if handle valid, try function address. if (hinstlib != null) { procadd = (myproc) getprocaddress(hinstlib, "simple.dll"); // if function address valid, call function. if (null != procadd) { fruntimelinksuccess = true; (procadd) (l"message sent dll function\n"); } // free dll module. ffreeresult = freelibrary(hinstlib); } // report failures if (! fruntimelinksuccess) printf("unable load dll or link functions\n"); if (! ffreeresult) printf("unable unload dll\n"); //
i hope made easy understand
you can see in moduleservice implementation in indiezen core library. treat .dll , .so "module". in plugin system have standard every module implements 1 , 1 exported function, getmodule()
in example, pick()
in use case.
my example returns in implementation of i_module interface. in example, modules collections of plugins, thing can implementation of i_plugin, in turn can used gain access class factories, , these class factories construct objects (extensions) implement pre-defined interfaces (extension points).
i know that's overkill example, code quite easy follow; feel free copy/paste subsets can use.
one key thing not use _declspec(dllimportorexport)
on pick
function; should exporting function , not importing it. should not linking these dll's main application, nor should include dll's header file main application. give flexibility of being able import 2 separate dll's expose same function (pick
in case) without having linking errors. give advantage of not knowing names of dll's until runtime (where possibly may want configuration or gui let user pick players).
my implementation, reference counting, class factory, etc give added advantage in have 2 players implemented within same dll play against each other.
Comments
Post a Comment