5YrsLaterDBA
5YrsLaterDBA

Reputation: 34760

how to call a method with string& parameter by using char*?

I have a C++ dll from other company. there is a method with a string& msg parameter, void methodA(string& msg);

What I have now is a char* with length which is big enough to take the msg from methodA. I want to call methodA to get message back from methodA.

Can I do it? how? thanks,

Upvotes: 1

Views: 471

Answers (4)

Edward Strange
Edward Strange

Reputation: 40859

Create a string out of your char* and pass it to methodA. That's how I'd do it.

Not sure what you're looking for here.

Note: Oh, I see it. Took me a moment.

std::string my_msg;
methodA(my_msg);
strcpy(my_char_star, my_msg.c_str());

I do have to say that this is basically exactly the opposite of the kind of code you should be writing. You should be using std::string or std::vector to provide char* buffer arguments, not char* to replace std::string.

Upvotes: 2

Greg Domjan
Greg Domjan

Reputation: 14105

Yes you can.

#include <string>

void yourfunc( char * mymsg, int len ) {
  string msg;
  methodA(msg);
  if( msg.length() < len ) {
    strncpy( mymsg, msg.c_str(), len );
  } else { // FAIL }
}

Upvotes: 1

Evan Teran
Evan Teran

Reputation: 90432

Sounds like you will need to use a pattern like this. It is unclear whether the paramter is an in/out or simply an out parameter. So you'll need one of these...

IN/OUT:

const char s[BIG_ENOUGH] = "whatever";
std::string str(s);
methodA(str);
// str should now have the response according to your API description

OUT:

std::string str;
methodA(str);
// str should now have the response according to your API description

// if you need to result in `s`...
strncpy(s, str.c_str(), BIG_ENOUGH);
s[BIG_ENOUGH - 1] = '\0'; // just to be safe

Upvotes: 3

fredoverflow
fredoverflow

Reputation: 263128

#include <algorithm>

void foo(char* buffer)
{
    std::string str;
    methodA(str);
    std::copy(str.begin(), str.end(), buffer);
    buffer[str.size()] = 0;
}

Upvotes: 4

Related Questions