简体   繁体   中英

How do I pass a LPCSTR to a c++ function convert to string and return a LPCSTR?

I have a C++ API function that is called by Install Shield via InstallScript:

SQLHELPER_API LPCSTR GetAvailableAppName(LPCSTR appNameP)
{
    //return "this works just fine";
    std::string newAppName = "I work, maybe?";
    LPCSTR returnVal = newAppName.c_str();
    return returnVal;
}

The only thing that returns is an empty string. If I just return passed in variable "appNameP" it returns that just fine as well.

My main issue is that I need to pass in a LPCSTR and perform some string operation on it.

A LPCSTR is the same as const char * .

Passing a C-style string like that to a function call is fine.

Returning a pointer to a local function variable is not fine, because this local variable doesn´t exist anymore after the function ends. As soon as you´re using the pointer in main (or whereever the function was called), it points to a memory which doesn´t belong to you anymore, and the value may have changed already.

There are several possibilites, each with a downside:

  1. Using only memory you got as parameter (eg. appNameP , because this has to be something from outside and will still exist after the function ends). Downside: You need to pass something fitting for that purpose => the function signature or at least the requirements for the parameters changes, and you´ve to check/change how it is called.

  2. Allocating something with new . Downside: Somewhere later, outside, delete[] have to be called.

  3. Returning something like std::string . Downside: As in #1, the function signature changes, and you´ve to change how it is called.

If InstallShield calls this function itself:

What InstallShield expects you to do should be somewhere in the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM