Is there an direct way to manage C++/CLI Strings in a wrapper to char* parameter for native C++ method?!
example:
void Test::TestFunc(System::String ^%str)
{
// right conversion to char* and consider the reference
}
native C++ function:
void TestB::Func(char *str)
{
...
}
my tricky way:
void Test::TestFunc(System::String ^%szRecvBuffer)
{
pin_ptr<const wchar_t> szRecvBufferP = PtrToStringChars(szRecvBuffer);
// Convert to a char*
size_t origsize = wcslen(szRecvBufferP) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
c开发者_高级运维har nstring[newsize];
wcstombs_s(&convertedChars, nstring, origsize, szRecvBufferP, _TRUNCATE);
strcat_s(nstring, " (char *)");
char *szRecvBufferCh = nstring;
m_object->TestCommand(szRecvBufferCh); // parameter char*
System::String ^tmp = gcnew System::String(szRecvBufferCh);
szRecvBuffer = tmp;
}
greets leon22
You're doing a lot manually that the runtime will take care of for you.
void Test::TestFunc(String^% szRecvBuffer)
{
using System::Runtime::InteropServices::Marshal;
IntPtr memHandle = Marshal::StringToHGlobalAnsi(szRecvBuffer);
try
{
char* const str = static_cast<char*>(memHandle.ToPointer());
m_object->TestCommand(str);
szRecvBuffer = gcnew String(str);
}
finally
{
Marshal::FreeHGlobal(memHandle);
}
}
If you're using VC++ 2010, you can use std::unique_ptr<>
with a custom deleter to avoid using try..finally
, ultimately cutting the number of lines of code in half.
If the char*
is an output parameter, then in C++/CLI you must pass System::StringBuilder^
If you search for "System::String" with Google, the second link is How to convert from System::String* to Char* in Visual C++ . This is obviously a FAQ!
(There appear to be about 5 different ways depending on the specifics of the conversion required, so I won't summarise them here: go read the article.)
You can't avoid having conversions in both directions, because System::String
uses wchar_t
, and a Unicode->Multibyte conversion is necessary to get char
from that.
But marshal_as
should make the conversion much easier.
精彩评论