2010년 1월 6일 수요일
[.NET Compact Framework-C#] 화면캡쳐-CopyFromScreen
[.NET Compact Framework-C#] Control Double Buffering
2010년 1월 5일 화요일
[.NET Compact Framework-C#] 리소스 이미지 속도개선
[.NET Compact Framework-C#] Native DLL(Marshaling) 사용 시 주의할 점
IntPtr pAbc = Marshal.AllocHGlobal(12);
// 관리되지 않는 메모리 사용구간: 시작
SetABC(pABC);
SetA(10);
int a = GetA();
...
// 관리되지 않는 메모리 사용구간: 끝
Marshal.FreeHGlobal(pABC);
2009년 11월 12일 목요일
[.NET Compact Framework-C#] Reflection을 이용한 인스턴스 생성하기
Reflection 을 이용하여 인스턴스를 생성하는 방법으로 .NET Framework 에서도 공통적으로 사용할 수 있을 것으로 예상되지만 일단 .NET Compact Framework 에서 확인한 사항이다.
1. 일반적인 인스턴스 생성
- 클래스 이름 문자열로 A라는 클래스의 인스턴스를 생성하려면 다음과 같이 한다.(GetType 내의 인자는 클래스의 full path를 사용해야 한다.)
System.Type type = System.Type.GetType("alpha.A");
A a = (A)System.Activator.CreateInstance(type);
- 위 구문은 다음과 같은 작동을 한다.
A a = new A();
2. 외부 DLL 내의 인스턴스 생성
- 클래스 이름 문자열로 import.dll 이라는 외부 DLL내의 B라는 클래스의 인스턴스를 생성하려면 다음과 같이 한다.(GetType 내의 인자는 클래스의 full path를 사용해야 하며 import.dll은 실행파일과 같은 경로에 있다고 가정한다.)
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(@".\import.dll");
System.Type type = assembly.GetType("alpha.B");
B b = (B)System.Activator.CreateInstance(type);
3. 활용
아래 예제는 만들어진 Base 클래스를 상속받은 실행파일 내의 R001 클래스와 Import.dll 내의 R002 클래스를 생성하고 실행하는 예제이다. 자세한 내용은 첨부된 소스를 참고한다.
예제소스 다운로드
private void buttonRun_Click(object sender, EventArgs e)
{
textBoxResult.Text = "";
// 클래스 이름이 입력되었는지 검사한다.
if (textBoxClassName.Text.Length == 0)
{
MessageBox.Show("Must input class name!", "Notice", MessageBoxButtons.OK,MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return;
}
Type type = null;
try
{
// Import.dll을 로드한다.
Assembly assembly = Assembly.LoadFrom(@".\Import.dll");
// 로딩된 DLL에서 클래스 타입을 얻는다.
type = assembly.GetType("Kr.Vsys.Test.Reflection." + textBoxClassName.Text);
// 클래스가 없을 경우 예외를 발생시킨다.
if (type == null)
{
throw new Exception();
}
}
catch (Exception)
{
// DLL이 없거나 DLL내에 원하는 클래스가 없을 경우 실행파일에서 클래스 타입을 얻는다.
type = Type.GetType("Kr.Vsys.Test.Reflection." + textBoxClassName.Text);
}
// 실행파일과 DLL에 모두 클래스가 없을 경우 메시지 박스를 출력한다.
if (type == null)
{
MessageBox.Show("Can't find class : " + textBoxClassName.Text, "Notice", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
return;
}
// 얻은 클래스 타입의 인스턴스를 생성한다.
Base instance = (Base)System.Activator.CreateInstance(type);
// 화면에 출력한다.
string result = "";
result += "- Class Name(Full Name)\r\n";
result += " " + instance.GetType().FullName + "\r\n";
result += "- Result\r\n";
result += " " + instance.run() + "\r\n";
textBoxResult.Text = result;
}