Re: How to call DLL with classes?
- Posted by mattlewis (admin) Sep 18, 2013
- 1588 views
I need to use DLL, that have got classes. How to do it? Some info from official documentation:
C++ is not easy to use from a DLL. The reason for this is that C++ compilers mangle the names in order to add class and parameter and return type information to the exported symbols. It's possible to use these mangled names in your #define_c_func calls, and then typically you'd pass the this pointer as the first parameter, with the normal parameters following that. This is very fragile, however, as the mangling is different from compiler to compiler, even different versions of the same compiler. If you only need to call a few things, it might not be too bad.
An easier way is to write a thin C++ wrapper with an "extern C" interface. You'll need to add the this pointer as an explicit parameter. This is the approach I've taken with wxEuphoria. So for the following:
class OCRSource { public: OCRSource(); OCRSource& BmpFile(const char *bmpFileName); OCRSource& Wnd(HWND); OCRSource& Rect(int ax, int ay, int bx, int by); };
...you might wrap this as:
extern "C " { OCRSource * new_OCRSource(){ return new OCRSource(); } OCRSource & OCRSource_BmpFile( OCRSource &ocr, const char *bmpFileName ){ return ocr.BmpFile( bmpFileName ); } /* etc... */ }
...and then use it something like:
constant NEW_OCRSOURCE = define_c_func( OCR_DLL, "new_OCRSource", {}, C_POINTER ), OCRSOURCE_BMPFILE = define_c_func( OCR_DLL, "OCRSource_BmpFile", { C_POINTER, C_POINTER }, C_POINTER ) atom ocr = c_func( NEW_OCRSOURCE, {} ) atom file_ptr = allocate_string( "my.bmp" ) c_func( OCRSOURCE_BMPFILE, { ocr, file_ptr } ) -- etc...
Matt