플밍

C++ <=> C# string 데이타 교환 본문

프로그래밍/C/C++

C++ <=> C# string 데이타 교환

너구리안주 2013. 11. 4. 13:18

C++ 로 만든 DLL과 C#의 클라이언트가 문자열을 주고 받을때는 int* 형을 쓰면 쉽다


C++ : dll 파일

#include <atlbase.h>
#include <atlconv.h>

extern "C" DLLTYPE int* test(int* str){
    static wstring s = CA2CT((char*)str); //unicode 형으로 바꿔준다
    s.append(L"--A"); //문자 추가
           
    return (int*)s.c_str();
}

#ads_1

C# : dll Client


public partial class Form1 : Form{

[DllImport("AutoPost.dll")]
public static extern IntPtr test(char[] str);  // c++ 에서 보내온 int* 형을 IntPtr 형으로 받는다

......

private void button4_Click(object sender, EventArgs e){
    String str = "하하하";
    char[] cstr = str.ToCharArray(); //char[] 형으로 변환한다

    IntPtr s = test(cstr);

    String str2 = Marshal.PtrToStringUni(s); //포인터형을 unicode스크링으로 변환한다
    MessageBox.Show(str2);
           
}

}


결과 (MessageBox 창으로 출력) >> 

하하하--A

#ads_2

Comments