View Single Post
  #1 (permalink)  
Old 11-07-2006, 06:29 AM
Minsc Minsc is offline
Senior Member
 
Join Date: Nov 2006
Posts: 315
Minsc is on a distinguished road
Default Function pointers instead of dlls in C++

Something I'm screwing around with.

Use this to extract a function:
Code:
//Broke some rules here...
#include <iostream.h>
#include <fstream.h>
char *blah="Blahhahah";

void fc() { cout << blah << blah[0] << blah[3] << blah[5]; }
typedef void (*fctype)();
fctype funcp;

int main() {
    funcp=fc;
    unsigned __int16 *fdat=(unsigned __int16*)funcp;
    //Not sure how to determine this exactly but it's close to the file size of the exe.
    void *nfunc=malloc(/*587370*/400000);
    for (int x=0;x</*587370*/400000;x++) *(((char*)nfunc)+x)=*(((char*)funcp)+x);
    ofstream exc("exc.exf", ios::out|ios::binary|ios::trunc);
    exc.write((char*)nfunc, 400000);
    exc.close();
    while(1);
}
And this will read the file and execute the function:
Code:
#include <iostream.h>
#include <fstream.h>
char *blah="Blahhahah";

void fc() { cout << "Orange"; }
typedef void (*fctype)();
fctype funcp;

int main() {
    ifstream exc("exc.exf", ios::in|ios::binary|ios::ate);
    int excs=exc.tellg(); exc.seekg(0);
    void *fdat=(void*)(new __int8[excs]);
    exc.read((char*)fdat, excs);
    funcp=(fctype)fdat;
    //funcp=(fctype)nfunc;
    (*funcp)();
    while(1);
}
Some restrictions that I know of:

-String constants aren't stored
-The second code's fc has to do something.
-I can't get cin to work for strings, just cout. (although you could probably write another function to cin stuff and use that)
-Calling other functions doesn't work but it can call itself.
-I suppose a lot of this depends on the compiler.
-I've never made a DLL and never directly used one in C++ so I don't really know if this is like one or not.
-You can use function pointers to call functions.
-Keep everything above the function declaration about the same...

Last edited by Minsc : 11-07-2006 at 07:07 AM.
Reply With Quote