string - C++/CX: Why doesn't returning a StringReference work like passing one as an argument? -


platform::stringreference exists can pass const wchar_t* across abi boundary function accepting string^ without making copy. stringreference implicitly converts string^ internal pointer matches original const wchar_t*. verified following code; if step through find pz == z:

void param(string^ s) {     const wchar_t* z = s->data(); }  app::app() {     std::wstring p = l"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";     const wchar_t* pz = p.c_str();     param(stringreference(pz)); } 

however, trying return stringreference doesn't seem work same way , i'm curious why. if have function returns string^ , return stringreference same implicit conversion operator called, when caller gets string^ has different internal data pointer contains copy. here's code tries it:

string^ ret() {     std::wstring s = l"12345678901234567890123456789012345678901234567890";     const wchar_t* z = s.c_str();     return stringreference(z); }  app::app() {     string^ r = ret();     const wchar_t* rz = r->data(); } 

that code verifies in 2 ways: first, if step through you'll find z != rz , second, r ends pointing valid string rather garbage, copy must have been made because original string freed @ end of ret.

i tried returning via out parameter, same results straight return (z != oz , o ends valid string):

void out(string^* r) {     std::wstring s = l"12345678901234567890123456789012345678901234567890";     const wchar_t* z = s.c_str();     *r = stringreference(z); }  app::app() {     string^ o;     out(&o);     const wchar_t* oz = o->data(); } 

is there way return stringreference across abi boundary in same way can pass one? imagine behavior depend on language of caller , how language marshals strings winrt, seems @ least c++/cx caller ought able it.

no can't return stringreference across abi boundary. returning stringreference across abi boundary similar (but not identical) returning address of local variable. that's because whole point of stringreference stringreference doesn't allocate new memory.

consider happen if return stringreference across abi boundary. happen if had:

string^ returnastring() {     const wchar_t buffer[500] = "mystring";     return stringreference(buffer); } 

the stringreference wrapper around stack allocated buffer. , can't return across abi boundary (the stack storage reclaimed routine exits).

instead need return real platform::string - platform::string contains copy of string data , can safely returned caller.


Comments

Popular posts from this blog

javascript - JS causing window size to be bigger than necessary - Dropdown bug -

php - Calling a template part from a post -

How to mention the localhost in android -