Thursday, March 24, 2011

Is there a way to call an unmanaged (not COM) dll from C# application?

Hello,

Is there a way to use (reference) a DLL written in an unmanaged C++ (not a COM library) in my C# application?

When I try to reference it from within Visual Studio, I get 'not a COM object' error message.

Maybe there is some kind of translator\router that would COMify my DLL reference? I have no clue how COM and COM interop work, since I started programming when this was already unnecessary for me.

Thank you.

From stackoverflow
  • See "Consuming unmanaged DLL functions" topic on MSDN:

    http://msdn.microsoft.com/en-us/library/26thfadc.aspx

    There is no need to add any COM proxy, .NET can consume DLLs directly using the [DllImport] attribute. You also have full control over the marshalling between .NET and the unmanaged DLL by specifying additional attributes.

  • You need to use the DllImport attribute. Here's an example for the Win32 PostMessage function:

    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool PostMessage(IntPtr handle, int message, IntPtr wparam, IntPtr lparam);
    
    greg7gkb : What is the [return: ] tag for? -g
    Joe : In this example, it specifies that the MarshalAs attribute applies to the return value of the function.
  • Joe already answered this, so I'm going to tack this on - to save yourself some time and not having to dig up and mangle function signatures, P/Invoke has a pretty complete library of Win32 signatures, in the form of both a wiki AND a Visual Studio plugin!

    Check it out at P/Invoke

0 comments:

Post a Comment