0
$\begingroup$

Rosanswers logo

Hi, I tried to do the tutorial writing a simple publisher and subscriber in c++ and it works.
Now i must use a function with argument the string that was subscribed, but i received the error: argument incorrect. This is the code:

void chatterCallback (const std_msgs::String::ConstPtr& msg) {
ROS_INFO("I heard: [%s]\n", msg->data.c_str());
my_function(msg->data); //error
// i also tried msg->data.c_str()
} void my_function(char* c) ....

any suggestion?
thanks


Originally posted by mrpiccolo on ROS Answers with karma: 36 on 2013-02-08

Post score: 1


Original comments

Comment by Jeffrey Kane Johnson on 2013-02-09:
What is the signature of my_function?

Comment by dornhege on 2013-02-09:
Also relevant: Does my_function need a non-const char* or is the just an old-style definition. If it doesn't change it, you could get away with just passing in the string data.

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

msg->data is of type string and ur function input argument is of type char*. Therefore u cannot directly pass either msg->data or msg->data.c_str() as argument and since u cannot change ur function argument i suggest following. Add this to ur subscriber callback

char *c; c=new char[sizeof(msg->data)]; c=&what[0]; myfunction(c)

This should work.

PS.Let me know if this doesnt work or any of the assumptions i made regarding ur problem is wrong.


Originally posted by ayush_dewan with karma: 1610 on 2013-02-09

This answer was ACCEPTED on the original site

Post score: 0


Original comments

Comment by dornhege on 2013-02-09:
This looks like a memory leak to me. You are reassigning the pointer to c and forgetting the newly allocated memory. In addition sizeof does NOT return the length of the string.

Comment by Jeffrey Kane Johnson on 2013-02-09:
I think you're looking for the strcpy function; just re-assigning the pointer won't change anything.

Comment by mrpiccolo on 2013-02-09:
thanks i tried strcpy(c,msg->data.c_str()); myfunction(c); and now work, because strcpy convert const char* to char*.

Comment by tfoote on 2013-02-11:
@mrpiccolo please accept this answer using the checkmark on the left side so others know your question is resolved.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.