calling a COM object from c#

I am calling a COM object from c# using this code:

string sProgID = "IData.Update";
// get the type using just the ProgID
Type oType = Type.GetTypeFromProgID (sProgID);

if (oType != null)
{
try
{
Object MyApp;
MyApp = Activator.CreateInstance(oType);

object[] args = new Object[7];
args[0] = args[1] = args[2] = args[3] = args[4] = args[5] = args[6 ] = true;
oType.InvokeMember("uf_run_updates", BindingFlags.InvokeMethod, null, MyApp, args);

MyApp = null;
oType = null;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}

My problem is this:
I am calling a com object that opens a Sybase database to update the data, then when my code is finished, the com object should close the database. What is happening though is that the database remains open (I can see the "SQL" in the notification area).

The MSDN help states that the InvokeMethod should not be called from managed code
"This method is for access to managed classes from unmanaged code, and should not be called from managed code."

Should I be using a different method to call into a com object Or am I not releasing the objects correctly

tia,
flynn


Answer this question

calling a COM object from c#

  • danidin

    I found the "FinalReleaseComObject" method in the MDSN help and gave that a try, but still no luck. Even though the return value from "FinalReleaseComObject" is 0, the COM object doesn't seem to die off.

    string sProgID = "IData.Update";
    // get the type using just the ProgID
    Type oType = Type.GetTypeFromProgID (sProgID);

    if (oType != null)
    {
    try
    {
    Object MyApp;
    MyApp = Activator.CreateInstance(oType);

    object[] args = new Object[7];
    args[0] = args[1] = args[2] = args[3] = args[4] = args[5] = args[6 ] = true;
    oType.InvokeMember("uf_run_updates", BindingFlags.InvokeMethod, null, MyApp, args);

    // added just to "prove" that MyApp is a valid COM object
    if (System.Runtime.InteropServices.Marshal.IsComObject(MyApp))
    {
    // this line displays a "0", meaning that there are no more references
    Console.WriteLine(System.Runtime.InteropServices.Marshal.FinalReleaseComObject(MyApp));
    }
    }
    catch (System.Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }


  • Vivek Puranik

    The object I am calling was created in Delphi. It doesn't show up the References->Com tab so we are limited to calling it as shown above.

  • Tynman

    You should add a reference to your COM library and work with the object as you would do with any .NET object.


  • Sandipan Deb

    The solution was to programatically call the garbage collector after calling "FinalReleaseComObject"

    GC.Collect();
    GC.WaitForPendingFinalizers();


    Thanks to all who offered suggestions.

  • PavelBx

    is this a COM Object

    Try using it as an Unsafe code. With DllImport and

    public static extern unsafe void

    See if that helps



  • calling a COM object from c#