Pregunta

Tengo un objeto COM que estoy tratando de envolverme en una clase C # para que esté disponible más fácilmente para otras aplicaciones que deseen consumirla.

Tengo el siguiente código que crea una instancia del objeto COM, y luego usar la reflexión hace una llamada a un método para recuperar los datos del usuario. Este código funciona bien cuando se encuentra en una página ASPX.

object jdObj = Server.CreateObject("jd_api.UserCookie");
string username = jdObj.GetType().InvokeMember("GetUserName", System.Reflection.BindingFlags.InvokeMethod, null, jdObj , null).ToString();

Sin embargo, cuando muevo el código a un archivo de clase (JD_API.CS) para abstraerlo desde el sitio web real, ya no puedo hacer que funcione. Por ejemplo, tengo el siguiente método estático que se declara como tal:

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;
}

Desafortunadamente, el objeto del servidor está restringido a algunas bibliotecas ASP.NET que se incluyen de forma predeterminada en aplicaciones web, por lo que el código anterior fue un no-Go. Entonces, en este punto, decidí intentar crear una instancia del objeto COM, como tal:

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;
}

Sin embargo, en el tiempo de ejecución, recibo un error que dice: " intentó leer o escribir la memoria protegida. Esto es a menudo una indicación de que se corrompe la otra memoria. ".

No estoy seguro de dónde ir desde aquí. Cualquier ayuda sobre cómo abstractar creación de una instancia de este objeto COM a una capa que no está dentro de la aplicación web en sí se apreciaría enormemente. ¡Gracias !!

¿Fue útil?

Solución

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.

Otros consejos

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!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top