0
votes

I currently have a C++ sample calling for a C++ DLL function this way:

typedef BOOL(__stdcall *f_funci)(const char*, char*);

HINSTANCE hGetProcIDDLL = LoadLibrary(L"myDLL.dll");
f_funci DoSmth= (f_funci)GetProcAddress(hGetProcIDDLL, "function");

std::string test = "The cake is a lie, it's actually a Brownie...";

char *out = new char[124];
DoSmth(&test[0], out);

And the DLL function prototype:

BOOL function(const char *in, char *out){}

The problem is, when I call this DLL function, I got a totally random result at in[x] (whatever x value) (using Visual Studio debugger).

However, if I simply paste this function inside my .cpp, in[x] is always the result I would expect to have.

What I verified:

  • DLL function's calling convention is stdcall, as expected.
  • Both the sample and the DLL are in the following context - Debug - x64 -

What I think it could possibly come from but don't know enough to ensure a Yes/No answer:

  • Memory management difference between a "simple call" and a GetProcAddress?
  • Debugger issue (would be weird considering the out value is also false in dll call case)
  • Other?

Please consider asking for details if something is unclear.

1
Just curious... change std::string test to an array of charand see if the behavior is any different. - ap-osd
@ap-osd: You asked for that clarification in your comment, that should have been enough; I flagged your (not-really-being-an-) answer (which is really just re-stating the above question) for deletion. Especially since passing the result of c_str() / data() to a function taking a C string (const char *) is very much well-defined; that part of your "answer" is off the mark -- and even while not being that well-defined, even passing &test[0] should not be a problem. - DevSolar
@DevSolar - I just wanted to highlight the fact that the internal memory of std::string can change and is not reliable to hold on it. See references cplusplus.com/reference/string/string/c_str and en.cppreference.com/w/cpp/string/basic_string/c_str. In any case, I will limit my answer to the specific problem. - ap-osd
@ap-osd: It is no more or less unreliable as passing a const char * directly. If you are looking at single-thread it is safe, if you are looking at multithreading it is safe unless you start modifying the string object (just like you could be modifying the C string object, e.g. freeing or reallocing its memory). It's a red herring. - DevSolar
@DevSolar - In theory that is fair. But I've had similar problems passing std::string across dlls. Maybe you can explain better as to why it happens and I will be happy to delete my "incorrect" answer. - ap-osd

1 Answers

0
votes

Hum... I found the solution but i don't know how it could have solved anything...

I actually just recompiled the dll (using the same options, same format and stuff) and now the results are fine and it works well.

If someone has an explanation or a clue for that, i'm in.

Thanks for all replies and help !