COPYDATASTRUCT 의

cbData에 숫자를, lpData에 문자열만 넣어서 

간단한 자료만 송수신 하는 예제 코드




송신부 (C#)

        public struct COPYDATASTRUCT

        {

            public IntPtr dwData;

            public int cbData;

            [MarshalAs(UnmanagedType.LPStr)]

            public string lpData;

        }


        private void OnButtonSendClick(object sender, EventArgs e)

        {

            string msg = this.tbMsg.Text.Trim();


            if (string.IsNullOrEmpty(msg))

            {

                MessageBox.Show("메세지를 입력해주세요");

                return;

            }


            IntPtr hwndRcvr = FindWindow(null, "CppReceiveWM_COPYDATA"); //"LHJ WINDOW");

//                byte[] buff = System.Text.Encoding.Default.GetBytes(msg);


                COPYDATASTRUCT cds = new COPYDATASTRUCT();

                cds.dwData = IntPtr.Zero;

//                cds.cbData = buff.Length + 1; //+1을 빼면 수신측에서 cds.lpdata의 뒤에 이상한 글자 붙음.

                cds.cbData = msg.Length+1; //+1을 빼면 수신측에서 cds.lpdata의 뒤에 이상한 글자 붙음.

                cds.lpData = msg;


                SendMessage(hwndRcvr, WM_COPYDATA, 0, ref cds);

        }





수신부 (C++)

 : memcpy_s(.) 을 없애서 빠른 응답속도를 지원토록 함


typedef struct tagCOPYDATASTRUCT2 {
    ULONG_PTR dwData;
    DWORD cbData;
     PVOID lpData;
} COPYDATASTRUCT2, *PCOPYDATASTRUCT2;


INT_PTR CALLBACK DialogProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)

{

//LHJ version //15.3.28 ---------------

    switch (message)

    {

case WM_COPYDATA:        

HandleWMCOPYDATA(hWnd, wParam, lParam);

break;

    default:

return DefWindowProc(hWnd, message, wParam, lParam);

    }

    return 0;

}


bool HandleWMCOPYDATA(HWND hWnd, WPARAM wParam, LPARAM lParam)

{

PCOPYDATASTRUCT2 pcds;

pcds = (PCOPYDATASTRUCT2)lParam;

try 

{

    // If the size matches

int nsize = pcds->cbData;

{

        SetDlgItemInt(hWnd, IDC_NUMBER_STATIC, nsize, TRUE);

//   std::wstring s1 = (LPCWSTR)pcds->lpData; //송신부가  [MarshalAs(UnmanagedType.LPStr)] 이므로 LPCWSTR은 에러


std::string s2 = (LPSTR)pcds->lpData;

std::wstring s1;

s1.assign(s2.begin(), s2.end());  


// SetDlgItemTextW(hWnd, IDC_MESSAGE_STATIC, (LPCWSTR)pcds->lpData); // >image);

SetDlgItemText(hWnd, IDC_MESSAGE_STATIC, s1.c_str()); // >image);




// The receiving application should consider the data (pcds->lpData) 

        // read-only. The pcds parameter is valid only during the processing 

        // of the message. The receiving application should not free the 

        // memory referenced by pcds. If the receiving application must 

        // access the data after SendMessage returns, it must copy the data 

        // into a local buffer. 

//        memcpy_s(&myStruct, sizeof(myStruct), pcds->lpData, pcds->cbData);

//        memcpy_s(&myStruct, nsize, pcds->lpData, pcds->cbData);


        // Display the MY_STRUCT value in the window.

        // Display the MY_STRUCT value in the window.

//        SetDlgItemInt(hWnd, IDC_NUMBER_STATIC, myStruct.Number, TRUE);

//        SetDlgItemText(hWnd, IDC_MESSAGE_STATIC, myStruct.Message);


//wchar_t text1[50000];

//mbstowcs(text1, myStruct.Message, strlen(myStruct.Message) + 1);

//        SetDlgItemText(hWnd, IDC_MESSAGE_STATIC, text1);


//        SetDlgItemInt(hWnd, IDC_NUMBER_STATIC, pMyStruct->Number, TRUE);

// LPCTSTR s2;

// s2 = (LPCTSTR) pMyStruct->Message;

//        SetDlgItemText(hWnd, IDC_MESSAGE_STATIC, s2);

    }

}

catch( int)

{

//MessageBox(hWnd, L"1", L"2", MB_OK);

}

return true;

}



Posted by 세모아
,


출처 : http://myblue0324.tistory.com/118


  1. // 방법1.  
  2. std::string str = "string";  
  3. std::wstring wstr = L"";  
  4.   
  5. wstr.assign(str.begin(), str.end());  
  6.   
  7. // 방법2.   
  8. USES_CONVERSION;  
  9.   
  10. std::string str = "string";  
  11. std::wstring wstr(A2W(str.c_str()));  


2. std::wstring을 std::string으로 변환.

  1. // 방법1.  
  2. std::wstring wstr = L"string";  
  3. std::string str = "";  
  4.   
  5. str.assign(wstr.begin(), wstr.end());  
  6.   
  7. // 방법2.  
  8. USES_UTF8_CONVERSION;  
  9.   
  10. std::wstring wstr = L"string";  
  11. str::string str(W2A(wstr.c_str()));  


위의 문자열을 CString형으로 변환하고자 할 경우에는 간단하게 아래와 같이 변경이 가능합니다.

  1. #ifdef _UNICODE  
  2.     std::wstring s = L"string";  
  3.     CString str(s.c_str());   
  4. #else  
  5.     std::string s = "string";  
  6.     CString str(s.c_str());   
  7. #endif  


Posted by 세모아
,

My 정리 :


std::string s2 = (LPSTR)pcds->lpData;


To "convert" a std::string to a LPCSTR depends on the exact context but usually calling .c_str() is sufficient.

This works.

void TakesString(LPCSTR param);

void f(const std::string& param)
{
    TakesString(param.c_str());
}

Note that you shouldn't attempt to do something like this.

LPCSTR GetString()
{
    std::string tmp("temporary");
    return tmp.c_str();
}

The buffer returned by .c_str() is owned by the std::string instance and will only be valid until the string is next modified or destroyed.



정의 -----------------------

LPSTR - (long) pointer to string - char *

LPCSTR - (long) pointer to constant string - const char *

LPWSTR - (long) pointer to Unicode (wide) string - wchar_t *

LPCWSTR - (long) pointer to constant Unicode (wide) string - const wchar_t *

LPTSTR - (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *

LPCTSTR - (long) pointer to constant TCHAR string - const TCHAR *



std:string 정의 페이지

http://www.cplusplus.com/reference/string/string/



원본 페이지 :



from: http://stackoverflow.com/questions/1200188/how-to-convert-stdstring-to-lpcstr


How can I convert a std::string to LPCSTR? Also, how can I convert a std::string to LPWSTR?

I am totally confused with these LPCSTR LPSTR LPWSTR LPCWSTR?

Are LPWSTR and LPCWSTR are the same?

shareimprove this question

str.c_str() gives you a const char *, which is an LPCSTR (Long Pointer to Constant STRing) -- means that it's a pointer to a 0 terminated string of characters. W means wide string (composed of wchar_t instead of char).

shareimprove this answer
4 
Minor picky point: on x64 LPCSTR would be a 64-bit pointer to a (constant) null-terminated string. –  Joel Jul 30 '09 at 14:41
1 
the C in LPCSTR stand for const not C –  mathk Jan 30 '13 at 9:14

Call c_str() to get a const char * (LPCSTR) from a std::string.

It's all in the name:

LPSTR - (long) pointer to string - char *

LPCSTR - (long) pointer to constant string - const char *

LPWSTR - (long) pointer to Unicode (wide) string - wchar_t *

LPCWSTR - (long) pointer to constant Unicode (wide) string - const wchar_t *

LPTSTR - (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *

LPCTSTR - (long) pointer to constant TCHAR string - const TCHAR *

You can ignore the L (long) part of the names -- it's a holdover from 16-bit Windows.

shareimprove this answer
3 
+1 Make it very easy. –  Sauron Jul 29 '09 at 13:24
   
Thank u very Much for ur support –  Cute Jul 29 '09 at 13:39

These are Microsoft defined typedefs which correspond to:

LPCSTR: pointer to null terminated const string of char

LPSTR: pointer to null terminated char string of char (often a buffer is passed and used as an 'output' param)

LPCWSTR: pointer to null terminated string of const wchar_t

LPWSTR: pointer to null terminated string of wchar_t (often a buffer is passed and used as an 'output' param)

To "convert" a std::string to a LPCSTR depends on the exact context but usually calling .c_str() is sufficient.

This works.

void TakesString(LPCSTR param);

void f(const std::string& param)
{
    TakesString(param.c_str());
}

Note that you shouldn't attempt to do something like this.

LPCSTR GetString()
{
    std::string tmp("temporary");
    return tmp.c_str();
}

The buffer returned by .c_str() is owned by the std::string instance and will only be valid until the string is next modified or destroyed.

To convert a std::string to a LPWSTR is more complicated. Wanting an LPWSTR implies that you need a modifiable buffer and you also need to be sure that you understand what character encodingthe std::string is using. If the std::string contains a string using the system default encoding (assuming windows, here), then you can find the length of the required wide character buffer and perform the transcoding using MultiByteToWideChar (a Win32 API function).

e.g.

void f(const std:string& instr)
{
    // Assumes std::string is encoded in the current Windows ANSI codepage
    int bufferlen = ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), NULL, 0);

    if (bufferlen == 0)
    {
        // Something went wrong. Perhaps, check GetLastError() and log.
        return;
    }

    // Allocate new LPWSTR - must deallocate it later
    LPWSTR widestr = new WCHAR[bufferlen + 1];

    ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), widestr, bufferlen);

    // Ensure wide string is null terminated
    widestr[bufferlen] = 0;

    // Do something with widestr

    delete[] widestr;
}
shareimprove this answer
   
How to Convert std::String to LPWSTR ??? –  Cute Jul 29 '09 at 13:44
   
Scholar and a gentleman! –  Russbear Aug 2 '11 at 22:02

Using LPWSTR you could change contents of string where it points to. Using LPCWSTR you couldn't change contents of string where it points to.

std::string s = SOME_STRING;
// get temporary LPSTR (not really safe)
LPSTR pst = &s[0];
// get temporary LPCSTR (pretty safe)
LPCSTR pcstr = s.c_str();
// convert to std::wstring
std::wstring ws; 
ws.assign( s.begin(), s.end() );
// get temporary LPWSTR (not really safe)
LPWSTR pwst = &ws[0];
// get temporary LPCWSTR (pretty safe)
LPCWSTR pcwstr = ws.c_str();

LPWSTR is just a pointer to original string. You shouldn't return it from function using the sample above. To get not temporary LPWSTR you should made a copy of original string on the heap. Check the sample below:

LPWSTR ConvertToLPWSTR( const std::string& s )
{
  LPWSTR ws = new wchar_t[s.size()+1]; // +1 for zero at the end
  copy( s.begin(), s.end(), ws );
  ws[s.size()] = 0; // zero at the end
  return ws;
}

void f()
{
  std::string s = SOME_STRING;
  LPWSTR ws = ConvertToLPWSTR( s );

  // some actions

  delete[] ws; // caller responsible for deletion
}
shareimprove this answer

The MultiByteToWideChar answer that Charles Bailey gave is the correct one. Because LPCWSTR is just a typedef for const WCHAR*widestr in the example code there can be used wherever a LPWSTR is expected or where a LPCWSTR is expected.

One minor tweak would be to use std::vector<WCHAR> instead of a manually managed array:

// using vector, buffer is deallocated when function ends
std::vector<WCHAR> widestr(bufferlen + 1);

::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);

// Ensure wide string is null terminated
widestr[bufferlen] = 0;

// no need to delete; handled by vector

Also, if you need to work with wide strings to start with, you can use std::wstring instead of std::string. If you want to work with the Windows TCHAR type, you can use std::basic_string<TCHAR>. Converting from std::wstring to LPCWSTR or from std::basic_string<TCHAR> to LPCTSTR is just a matter of calling c_str. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar (and its inverse WideCharToMultiByte) comes into the picture.

shareimprove this answer

The conversion is simple:

std::string str; LPCSTR lpcstr = str.c_str();

shareimprove this answer

Converting is simple:

std::string myString;

LPCSTR lpMyString = myString.c_str();

One thing to be careful of here is that c_str does not return a copy of myString, but just a pointer to the character string that std::string wraps. If you want/need a copy you'll need to make one yourself using strcpy.

shareimprove this answer
   
How to Convert std::String to LPWSTR ??? –  Cute Jul 29 '09 at 13:44

The easiest way to convert a std::string to a LPWSTR is in my opinion:

  1. Convert the std::string to a std::vector<wchar_t>
  2. Take the address of the first wchar_t in the vector.

std::vector<wchar_t> has a templated ctor which will take two iterators, such as the std::string.begin() and .end() iterators. This will convert each char to a wchar_t, though. That's only valid if the std::string contains ASCII or Latin-1, due to the way Unicode values resemble Latin-1 values. If it contains CP1252 or characters from any other encoding, it's more complicated. You'll then need to convert the characters.


Posted by 세모아
,