On Aug 29, 11:08 am, "Phlip" <phlip...@yahoo.com> wrote:
> brad.power wrote:
> > std::string s1 = "Hello, World";
> > call_some_function(s1.c_str()); //Pass a const char* to some api
> > m_stringvector.push_back(s1);
>
> > Now, once s1 goes out of scope, it will destruct. I assume the copy of
> > s1 sitting in the vector is exactly that - a copy. So the pointer
> > value of the vectors s1.c_str() would be different to the local
> > s1.c_str() (even though they would both contain the same string data).
> > This means that once s1 goes out of scope, my c_str() array pointers
> > that I have passed to external API's are invalid.
>
> Can you positively determine this? Can you read the API's source, or its
> documentation, or its tests?
>
> Can you do this?
>
> char yo[] = "hello world";
> call_some_function(yo);
> strcpy(yo, "bye-bye");
>
> What string comes out the other end of this API? I don't know about other
> programmers, but if I were writing a C API then I would take the Interface
> part very seriously, and would not abuse pointers to things my clients
> passed in.
So what you are asking is whether or not the other side of the API
takes a copy of the string or just uses whatever the passed pointer
points to? I have done a test and found that it doesn't make its own
copy - it just passes the pointer around internally. Thats actually
the problem I am trying to solve - I am making long-lived copies of
the data in my code so that the pointers passed will continue to be
valid, and I just wanted to see if my 'use a vector to keep track and
clean up' idea was a good one.
>
> > P.S. I tried to avoid threads, but the other api's I am working with
> > need me to use them, or hang the UI while I do some long task.
>
> In this case, you need to learn threading, and then use a semaphore to
> ensure your thread-side objects live as long as the thread. And you need to
> put your strings into a container (like your vector) which is itself a
> member of these thread-side objects. Put the entire object onto the side of
> your API - not just each danged string by itself.
>
That is exactly what I am doing. This container is sitting in a thread-
side object which is guaranteed to have the same lifetime as the
thread. The vector is meant to be an automatic clean up system, since
once I kick the thread off I want it to clean up after itself.
> And, are you absolutely certain your GUI will hang if you run the API? Does
> it have any timer or semaphore system you can use to strobe your GUI?
> Sometimes these systems are more robust...
Yep. I tried it without threads and it hung, and then I went to the
documentation, which told me to use threads. :)
>
> --
> Phlip
> http://www.oreilly.com/catalog/9780596510657/
> "Test Driven Ajax (on Rails)"
> assert_xpath, assert_javascript, & assert_ajax
Thanks for your help.