[英]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: 我有一个C ++ API函数,由Install Shield通过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.
如果我只是返回传入的变量“ appNameP”,那么它也可以返回。
My main issue is that I need to pass in a LPCSTR and perform some string operation on it. 我的主要问题是我需要传递LPCSTR并对其执行一些字符串操作。
A LPCSTR
is the same as const char *
. LPCSTR
与const char *
相同。
Passing a C-style string like that to a function call is fine. 将这样的C样式字符串传递给函数调用就可以了。
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. 一旦您在
main
(或调用该函数的任何地方)中使用指针,它就会指向一个不再属于您的内存,并且该值可能已经更改。
There are several possibilites, each with a downside: 有几种可能性,每个都有缺点:
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). 仅使用获得的内存作为参数(例如
appNameP
,因为它必须来自外部,并且在函数结束后仍然存在)。 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. 缺点:为此,您需要传递一些合适的东西=>函数签名或至少更改参数的要求,并且您必须检查/更改其调用方式。
Allocating something with new
. 用
new
东西分配东西。 Downside: Somewhere later, outside, delete[]
have to be called. 缺点:稍后,必须在外部某个地方调用
delete[]
。
Returning something like std::string
. 返回类似
std::string
。 Downside: As in #1, the function signature changes, and you´ve to change how it is called. 缺点:和#1一样,函数签名也会更改,您必须更改其调用方式。
If InstallShield calls this function itself: 如果InstallShield本身调用此函数:
What InstallShield expects you to do should be somewhere in the documentation. InstallShield希望您执行的操作应在文档中的某个位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.