Monday, July 27, 2009

How do I create and use a DLL?

I am use to writing command line based C code. I want to retain the code in proc1 (except for printf, although it could become a message box) but replace main with a simple GUI using MS VC. How do I make proc1 into a DLL? And how do I write C++ code to use that DLL?





extern void proc1(char *);





main()


{


char mystr[128]="output.txt\0";


char *str1;





str1=%26amp;mystr[0];


proc1(str1);


}





#include %26lt;stdlib.h%26gt;


#include %26lt;stdio.h%26gt;





void proc1(char *instr)


{


FILE *outptr;





outptr=fopen(instr,"w");





if(outptr==NULL)


{


printf("Could NOT create file (%s)\n",instr);


exit(0);


}


else


{


fprintf(outptr,"Add some text\n");


fprintf(outptr,"This is the file: %s\n",instr);


}


printf("File written: [%s]\n",instr);


}

How do I create and use a DLL?
It is a simple process. Just create a DLL VC++ project, and expose your intended function with a __declspec modifier as





extern "C" __declspec(dllimport) void proc1(char* instr);





for user code and





extern "C" __declspec(dllexport) void proc1(char* instr);





for the provider code.





To simplify this process you could make a common header file proc1.h having





#ifdef EXPORTING


extern "C" __declspec(dllexport) void proc1(char* instr);


#else


extern "C" __declspec(dllimport) void proc1(char* instr);


#endif





for your main file, simply include this header





#include "proc1.h"





for your proc1.c use an extra #define:





#define EXPORTING


#include "proc1.h"





Good luck


No comments:

Post a Comment