Error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'char*'

Hi.

It's my first post and I'm having a problem in C++ right now.

So I'm making a small thing that gets the program's file directory and then returns it in DLL C extern function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <windows.h>
#include <string>
#include <iostream>
#define cdll extern "C" __declspec (dllexport)
using namespace std;;

string ExePath() {
    char buffer[MAX_PATH];
    GetModuleFileName( NULL, buffer, MAX_PATH );
    string::size_type pos = string( buffer ).find_last_of( "\\/" );
    return string( buffer ).substr( 0, pos);
};

cdll char* exPath() {
    return ExePath();
};


I already tried to use c_str() function but it didn't work well.

I hope for your help. Thanks!
exPath() returns a char*. You need to make sure that wherever that pointer is pointing to remains valid.

Anything you create on the stack (i.e. not with static or some other such) inside a function vanishes when that function ends.

So if you try something like this:
1
2
3
cdll char* exPath() {
    return ExePath().c_str();
};


it won't work because the array of char that the returned pointer is pointing to will cease to exist (the array of char inside the string object), leaving you with a pointer to memory that could be anything.


Ideally, change exPath() to return a string. Can you change what exPath() returns?


Also, this function exPath(). Is this going to be called from other libraries or executable? That also adds complication.
Last edited on
1
2
3
4
5
6
cdll const char* exPath() {

    static const std::string path_str = ExePath();

    return path_str.c_str() ;
}
https://linux.die.net/man/3/dirname
1
2
3
4
5
char* ExePath(){
   static char buffer[MAX_PATH];
   GetModuleFileName( NULL, buffer, MAX_PATH );
   return dirname(buffer);
}


> I already tried to use c_str() function but it didn't work well.
c_str() will give you a const pointer to the buffer used by the string, the problem is that the string dies at the end of the function, so you are pointing to garbage.


as an alternative
1
2
3
cdll char* exPath() { //your client should `free()' the returned c-string
    return strdup(ExePath().c_str());
};
Topic archived. No new replies allowed.