Problem with LPSTR and managed c++ wrapper

I need to write a dll in a managed c++ wrapper

String* GetResponse(String* response)
{
// calling SendResponse()
}

for a dll with a function declaration
LPSTR SendResponse( LPSTR strResponse );

I have trouble writing this mc++ wrapper function passing parameters between String* and LPSTR. any help will be very much appreciated.
What's a String?
@kbw: This is C++/CLI (note he said "Managed"). He's talking about System::String.

@tenteddies: Not a lot of people are familiar with C++/CLI on these boards. I don't think you'll get much help to your problem here.
Wow, all that marshalling stuff ... ugh.
To start with, if String is System::String, the signature of the managed function should prob. be

1
2
3
4
String^ GetResponse(String^ response)
{
    // calling SendResponse()
}


(char* cf String^)

char* -> String^

System::String has a constructor that takes a char*, so you convert from char* to System::String by constructiing a new System::String (using gcnew)

1
2
const char* psz_msg= "Hello, world!";
System::String^ cli_msg = gcnew String(msg);


String^ -> char*

To go the other way, you need to use a marshalling function : StringToHGlobalAnsi -- here, cli_msg is a pre-exisiting, valid System::String^ variable.

1
2
3
4
5
char buffer[1024]; // need to be careful with buffer size in real code
IntPtr hglob = Marshal::StringToHGlobalAnsi(cli_msg);
char* msg = static_cast<char*>(hglob.ToPointer());
strcpy(buffer, msg);
Marshal::FreeHGlobal(hglob);


For more info, see

String Class
http://msdn.microsoft.com/en-gb/library/system.string.aspx
String Constructor (Char*)
http://msdn.microsoft.com/en-gb/library/6y4za026.aspx

How to convert from System::String* to Char* in Visual C++
http://support.microsoft.com/kb/311259

Andy

PS The above code needs to be in a managed code segment, of course.
Last edited on
Topic archived. No new replies allowed.