c++ DLL을 c#에서 사용시 질문입니다.
조회수 2845회
안녕하십니까(__)
c++ 에서 생성한 DLL 파일 문자열 함수에 대한 c#에서 처리때문에 질문 남깁니다.
[DLL]
#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <atlbase.h>
#include <Windows.h>
extern "C" __declspec(dllexport) int intOnTest2(int intA)
{
//입출력 숫자형
++intA; //입력받은 숫자에 +1
return intA;
}
extern "C" __declspec(dllexport) int* strOnTest3(int* strTemp)
{
static std::wstring s = CA2CT((char*)strTemp);
s.append(L"(T^T)");
return (int*)s.c_str();
}
[c#]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace CSwinformDLLTest
{
public partial class Form1 : Form
{
[DllImport("CtestDLL.dll", CallingConvention = CallingConvention.Cdecl)]
extern public static int intOnTest2(int intTemp);
[DllImport("CtestDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr strOnTest3(char[] strTemp);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(intOnTest2(int.Parse(textBox2.Text)) + " = intOnTest2(" + textBox2.Text + ")");
}
private void button2_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
char[] cstr = str.ToCharArray();
IntPtr s = strOnTest3(cstr);
string str2 = Marshal.PtrToStringUni(s);
Marshal.FreeHGlobal(s);
textBox2.Text = str2;
}
}
}
단순히 DLL에서 받은 문자열에 (TㅅT) 문자를 더하여 리턴해주는 함수를 c#에서 사용하려고 합니다. 인터넷을 뒤져가며 현제 위와 같은 코드를 만들었구요.
button2를 클릭 하였을때 textbox1에 text를 읽어와 strOnTest3 함수를 실행하여 (TㅅT)문자를 붙인 후 textbox2.text에 넣는 코드 입니다.
문제는 처음 버튼2 클릭 시 정상적으로 textbox1의 text가 옮겨 지게 되는데 두번 이상 클릭 시 변경 된 textbox1의 text 값이 아닌 최초 읽어들인 textbox1의 text값이 계속 (TㅅT) 만 추가되어 나오는 상황입니다.
Marshal.FreeHGlobal(s); 이 부분이 빠진거 같아 넣었더니 해당부분에서 작동이 중지됩니다.
어떤부분에서 잘못 된 건가요 알려주시면 감사 하겠습니다 (__)
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력