Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[question] how to get a string value by pointer #683

Closed
zhishupp opened this issue Aug 9, 2017 · 4 comments
Closed

[question] how to get a string value by pointer #683

zhishupp opened this issue Aug 9, 2017 · 4 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@zhishupp
Copy link

zhishupp commented Aug 9, 2017

I wrapped a C lib for using json.hpp, like this:

json_string = {"file":"/opt/test.conf"}

set json_string to a static json object

static json para = json::parse(json_string);

`
extern "C" const char*

get_json_string()

{

if (para["file"].is_string())     
            
{                        

    return para["file"].get<std::string>().c_str();      
           
}          

}
`

but actually, get_json_string cannot get the real address of para, so how to get a string value in this way ?

I don't want to use strcpy like this:
`
get_json_string(char* value)

{

if (para["file"].is_string())

{

    strcpy(value, para["file"].get<std::string>().c_str());

}

}
`

@zhishupp
Copy link
Author

zhishupp commented Aug 9, 2017

I find a way like this:

`
extern "C" const char*

get_json_string()

{

if (para["file"].is_string())

{

return para["file"].get<json::string_t*>()->c_str();      
 ----  or ----
return para["file"].get_ptr<json::string_t*>()->c_str();       

}

}
`

now I can get the correct data, is that right ?

and

get<json::string_t*>()->c_str(); or get_ptr<json::string_t*>()->c_str();

which one is corret, or better ?

@nlohmann
Copy link
Owner

nlohmann commented Aug 9, 2017

You should use get_ptr to be sure no copies are made:

return get_ptr<json::string_t*>()->c_str();

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Aug 9, 2017
@nlohmann
Copy link
Owner

Does this solve the issue?

@zhishupp
Copy link
Author

many thanks, issue has been solved ^^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants