12

I need a help on one question where I stuck while coding my app in MFC.

I am using CLR i.e Common Language Runtime in my application to integrate c# APIs. but now I stuck on converting System::String^ to CString. I am not able to do that.

I am using Following code.

String^ csPass = gcnew String(strPassword.GetBuffer());
array<Byte>^ Value = Encoding::UTF8->GetBytes(csPass);
for (int i = 0; i < Value->Length; i++ )
{
csPass += String::Format( "{0:X2}", Value[ i ] );
}

now I want to convert csPass to CString. Can any one help me on this. Thank you in advance.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
A B
  • 1,461
  • 2
  • 19
  • 54

3 Answers3

6

Got My answer. Thanks for your support @Elliot Tereschuk.

I have gone through some references like

  1. How to: Extend the Marshaling Library
  2. Overview of Marshaling in C++
  3. For CString.Format()

and

include header files

#include <msclr/marshal_windows.h>
#include <msclr/marshal.h>

using Library using namespace msclr::interop;

And finally My source code is.

String^ csPass = gcnew String(strPassword.GetBuffer());
array<Byte>^ Value = Encoding::UTF8->GetBytes(csPass);
for (int i = 0; i < Value->Length; i++ )
{
csPass += String::Format( "{0:X2}", Value[ i ] );
}

marshal_context^ context = gcnew marshal_context();

const char* str = context->marshal_as<const char*>(csPass);

csMyPass.Format(str);

csMypass is a CString type Variable. Thank you for support.

A B
  • 1,461
  • 2
  • 19
  • 54
  • I copied your codes to my project, but the compiler report that it cannot recognize this class: Encoding::UTF8->GetBytes(csPass), do you know why? thank you! – sunjinbo Mar 24 '16 at 15:07
  • @sunjinbo have u added the header files in your code. or refer http://stackoverflow.com/questions/6596242/net-systemstring-to-utf8-bytes-stored-in-char – A B Apr 06 '16 at 04:35
  • #include is not required for my environment. I modified code a little: auto context = gcnew marshal_context(); auto msgChars = context->marshal_as(csPass); CString csMyPass(msgChars); – HMartyrossian May 03 '19 at 19:57
5

Consider reading this MSDN thread about string conversions. Also, following discussions may be useful for you:

With this material you can find out how to do it and even post own solution as an answer

Community
  • 1
  • 1
Ilya Tereschuk
  • 1,204
  • 1
  • 9
  • 21
0

This is working for me, and it's much easier:

CString csPassAsCtring = CString(csPass)
Sergioet
  • 1,108
  • 13
  • 27