views:

355

answers:

3

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.

+5  A: 

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.

petr k.
+7  A: 

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);
Joe
What is the [return: ] tag for?-g
greg7gkb
In this example, it specifies that the MarshalAs attribute applies to the return value of the function.
Joe
+1  A: 

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

Bartek Tatkowski