开发者

php extension how to return a string from a method?

开发者 https://www.devze.com 2023-04-05 00:52 出处:网络
I have in [example.cc] a method : std::string Car::accelerate (std::string n) { cout<<n<<endl;

I have in [example.cc] a method :

std::string Car::accelerate (std::string n)
{
cout<<n<<endl;
return n;
}

I would like to call this method from a php extension

I wrote this in my [test_php.cc] extension:

 char *strr=NULL;
 int strr_len;
 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &strr, &strr_len) == FAILURE) {
        RETURN_NULL();
  }
  std::string s(strr)开发者_StackOverflow;
RETURN_STRING(car->accelerate(s),1);

I have the following error:

warning: deprecated conversion from string constant to ‘char*’
/home/me.cc:79: error: cannot convert ‘std::string’ to ‘const char*’ in initialization
/home/me.cc: At global scope:warning: deprecated conversion from string constant to ‘char*’

If i change the return_string(..) _ with a simple call car->accelerate(s); it works..it's true it doesn't print anything as a return function. need some help. appreciate


Given your recent comment I'll propose this as an (uneducated) answer.

RETURN_STRING() takes a const char* in it's first parameter. That's what you call a "C-String", and there is no automatic conversion from std::string to const char * (at least for the compiler).

What you want to do is pass a const char* as the first argument. To generate a const char* from a std::string you call the method c_str(). I.e. change your last line to:

RETURN_STRING(car->accelerate(s) . c_str(), 1);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号