tags:

views:

143

answers:

3

I'm trying to use the following code to convert a native string to a managed string in C++\CLI:

System::String^ NativeToDotNet( const std::string& input )
{
    return System::Runtime::InteropServices::Marshal::PtrToStringAnsi( (static_cast<LPVOID>)( input.c_str() ) );
}

I originally found the code here:

But when I try to build it throws the error:

syntax error : identifier 'LPVOID'

Any idea how to fix this?

+1  A: 

LPVOID is just an alias for void *. LP stands for "long pointer," which is an old-style way of saying "machine-sized pointer", either 32 or 64 bit depending on the process.

Just use static_cast<void *>

In one or more header files somewhere, there's a #define LPVOID (void *)

You haven't included such a file.

Drew Hoskins
That gives errors with: 'static_cast' : cannot convert from 'const char *' to 'void *'
Adam Haile
@Adam: ...which is quite reasonable. Any time you have a `void *`, you can expect to have to cast it to some other kind of pointer to do anything useful with it.
T.E.D.
no, it's having a problem casting the output of input.c_str() TO void *...
Adam Haile
You need to cast to <const void *>, or cast the const away by using const_cast<char *>.
Drew Hoskins
A: 

Casting to (same cv-qualifiers) void* is always implicitly possible, you should never see a cast trying to do so. The error is from trying to remove const with a static_cast

Try this, which also handles embedded NUL characters correctly:

using System::Runtime::InteropServices::Marshal::PtrToStringAnsi;
return PtrToStringAnsi( const_cast<char*>(&input[0]), input.size() );

The const_cast<char*> takes care of the stupidity which is the lack of const-correctness in .NET

Ben Voigt
+1  A: 

This crops up quite often in various guises - the simplest answer is: don't write your own function, see here: http://msdn.microsoft.com/en-us/library/bb384865.aspx

tragomaskhalos