我有一个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;
}
.

不幸的是,服务器对象仅限于Web应用程序中默认包含的一些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对象的实例的任何帮助,它将非常欣赏到不在Web应用程序本身的图层。谢谢!!

有帮助吗?

解决方案

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):

  1. Right Click "References" in your project
  2. Select "Add Reference"
  3. Selelct the "Com" Tab
  4. 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!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top