ASP.NET 클래스 파일에서 COM 개체를 사용하는 방법
-
14-11-2019 - |
문제
COM 객체가 있으며, C # 클래스에서 랩핑하려는 다른 응용 프로그램에서 더 쉽게 사용할 수 있도록하십시오.
COM 개체의 인스턴스를 생성 한 다음 반사를 사용하는 다음 코드가있어 사용자 데이터를 검색하는 메소드를 호출합니다. 이 코드는 ASPX 페이지에있을 때 잘 작동합니다.
object jdObj = Server.CreateObject("jd_api.UserCookie");
string username = jdObj.GetType().InvokeMember("GetUserName", System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();
.
그러나 코드를 실제 웹 사이트에서 추상화하기 위해 클래스 파일 (jd_api.cs)으로 코드를 이동하면 더 이상 작동하지 않습니다. 예를 들어, 다음과 같이 선언 된 다음 정적 메소드가 있습니다.
public static string GetUserName() {
object jdObj = Server.CreateObject("jd_api.UserCookie");
string username = jdObj.GetType().InvokeMember("GetUserName",
System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();
return username;
}
.
불행히도, 서버 객체는 웹 응용 프로그램에서 기본적으로 포함 된 일부 ASP.NET 라이브러리로 제한되므로 위의 코드는 이동하지 않았습니다. 그래서이 시점에서는 다음과 같이 COM 객체의 인스턴스를 만들기로 결정했습니다.
public static string GetUserName() {
Type type = Type.GetTypeFromProgID("jd_api.UserCookie");
object jdObj = Activator.CreateInstance(type);
string username = jdObj.GetType().InvokeMember("GetUserName", System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();
return username;
}
.
그러나 런타임에 "은 보호 된 메모리를 읽거나 쓰려고 시도하는 오류가 발생합니다. 이것은 종종 다른 메모리가 손상되었음을 나타냅니다. ". .
여기에서 어디로 가야하는지 확실하지 않습니다. 웹 응용 프로그램 자체 내에 있지 않은 레이어 에이 COM 개체의 인스턴스를 생성하는 방법에 대한 도움말은 크게 감사 할 것입니다. 고마워 !!
해결책
Declare DLL functions within a class. Then define a static method for each DLL function you want to call. The following code sample creates a wrapper named Win32MessageBox that calls the MessageBox function in User32.dll each time a .NET app calls the object Show method. It requeres the System.Runtime.InteropServices namespace.
using System;
using System.Runtime.InteropServices;
class Win32MessageBox
{
[DllImport("user32.dll")]
private static extern int MessageBox(IntPtr hWnd, String text,
String caption, uint type);
public static void Show(string message, string caption)
{
MessageBox(new IntPtr(0), message, caption, 0);
}
}
To call it, just type:
Win32MessageBox.Show("StackOverflow!", "my stack box");
The method where you call the above line doesn't need to be aware that it's a actually calling a function in an unmanaged DLL.
Resources: the MCTS Self-Paced Training Kit (Exam 70-536) by Tony Northrup.
다른 팁
Hove you tried usinsing interoperating
I've done the following in the past (working from memory so you might need to fiddle with this a bit):
- Right Click "References" in your project
- Select "Add Reference"
- Selelct the "Com" Tab
- Find and add your Com Instnace
In your class file
using yourComName;
public static string GetUserName()
{
yourComName.yourComClass jdObj = new yourComClass();
string username = jdObj.GetUserName(someParameters);
return username;
}
Hope this a) works and b) helps!