简体   繁体   English

有没有办法从C#应用程序调用非托管(不是COM)dll?

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

Is there a way to use (reference) a DLL written in an unmanaged C++ (not a COM library) in my C# application? 有没有办法在我的C#应用​​程序中使用(引用)用非托管C ++(不是COM库)编写的DLL?

When I try to reference it from within Visual Studio, I get 'not a COM object' error message. 当我尝试从Visual Studio中引用它时,出现“不是COM对象”错误消息。

Maybe there is some kind of translator\\router that would COMify my DLL reference? 也许有某种translator \\ router可以修改我的DLL参考? I have no clue how COM and COM interop work, since I started programming when this was already unnecessary for me. 我不知道COM和COM互操作的工作原理,因为我开始编程时对我来说已经不需要了。

Thank you. 谢谢。

You need to use the DllImport attribute. 您需要使用DllImport属性。 Here's an example for the Win32 PostMessage function: 这是Win32 PostMessage函数的示例:

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PostMessage(IntPtr handle, int message, IntPtr wparam, IntPtr lparam);

See " Consuming unmanaged DLL functions " topic on MSDN: 请参阅MSDN上的“使用非托管DLL函数 ”主题:

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

There is no need to add any COM proxy, .NET can consume DLLs directly using the [DllImport] attribute. 无需添加任何COM代理,.NET可以使用[DllImport]属性直接使用DLL。 You also have full control over the marshalling between .NET and the unmanaged DLL by specifying additional attributes. 您还可以通过指定其他属性来完全控制.NET和非托管DLL之间的编组。

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! 乔已经回答了这个问题,所以我要继续解决这个问题-为节省时间,而不必深入研究和破坏函数签名,P / Invoke具有相当完整的Win32签名库,以Wiki的形式提供和一个Visual Studio插件!

Check it out at P/Invoke P / Invoke签出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM