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.
std::string testto an array ofcharand see if the behavior is any different. - ap-osdc_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. - DevSolarstd::stringcan 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-osdconst 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. - DevSolarstd::stringacross dlls. Maybe you can explain better as to why it happens and I will be happy to delete my "incorrect" answer. - ap-osd