Exporting string values from a DLL...

Started by
2 comments, last by MJP 16 years, 2 months ago
How to? return (double) returns a number, so what should (double) be replaced with to return a string? I am using Bloodshed Dev C++.
Advertisement
The safest way is to have a function that takes a char* (and for added safety, the size of the buffer pointed to), and then have the function in the DLL fill that buffer with data using sprintf() or some similar function.

Another option would be to sprintf() (or similar) to a static buffer and return that.

Returning memory allocated from new or malloc, or returning a std::string isn't advisable, since the DLL and EXE may have different heaps.

EDIT: Actually, there's another way I thought of, which is even more horrible:
struct FixedString{   char buff[128];};FixedString GetDouble(){   FixedString ret;   snprintf(ret.buff, sizeof(ret.buff), "%f", someDouble);   return ret;}// Usage:printf("DLL returns %s\n", GetDouble().buff);

That returns an array of chars in a struct (There might be a way to do it without the struct, I'm not sure offhand) by value. But like I said, it's horrible.
If you want a DLL that just stores string values, then consider making a DLL that just contains string table resources. You can then use LoadLibrary() and LoadString() to get the strings without needing to manage character memory. However, I'm not familiar with DevCpp's resource editing capabilities; you'll need to consult your compiler's documentation to find out how to do that.
Quote:Original post by Evil Steve

Returning memory allocated from new or malloc, or returning a std::string isn't advisable, since the DLL and EXE may have different heaps.



AFAIK when the DLL versions of the VC++ CRT load the DLL, they both have the same heap manager. But of course your suggestion is probably the way to go, considering I have no idea how mingw handles heap management for DLL's.

Speaking of mingw, may I humbly suggest that you ditch DevC++ in favor of Visual C++? [smile]

This topic is closed to new replies.

Advertisement