【发布时间】:2011-12-24 10:40:25
【问题描述】:
我使用 Microsoft Visual Studio 2008 创建了一个 C# 应用程序,现在我想使用基于 C 的 DLL。
如何在 Visual Studio 2008 中将对该基于 C 的 DLL 的引用添加到我的 C# 应用程序?
【问题讨论】:
-
你试过什么?您阅读过哪些文档,文档中有哪些不明白的地方?
标签: c# c dll pinvoke dllimport
我使用 Microsoft Visual Studio 2008 创建了一个 C# 应用程序,现在我想使用基于 C 的 DLL。
如何在 Visual Studio 2008 中将对该基于 C 的 DLL 的引用添加到我的 C# 应用程序?
【问题讨论】:
标签: c# c dll pinvoke dllimport
您不能在 C# 或 VB.NET 项目中添加对本机(非托管)DLL 的引用。这根本不支持。引用仅适用于其他托管 DLL(即,您可能用 C# 或 VB.NET,甚至 C++/CLI 编写的那些)。
但是,您可以仍然使用该 DLL 中的代码。诀窍是使用与从 Win32 API 调用函数相同的 P/Invoke 语法在运行时动态调用它提供的函数。
例如,假设您使用 C++ 将以下代码编译成 DLL:
extern "C" {
__declspec(dllexport) void AddNumbers(int a, int b, int* result)
{
*result = (a + b);
}
}
现在,假设您将该 DLL 编译为名为 test.dll 的文件,您可以通过将以下代码添加到您的 C# 应用程序来调用该函数:
[DllImport("test.dll"), CallingConvention=CallingConvention.Cdecl)]
private static extern void AddNumbers(int a, int b, out int result);
public int AddNumbers_Wrapper(int a, int b)
{
int result;
AddNumbers(a, b, out result);
return result;
}
或者在 VB.NET 中,因为您显然正在使用它(尽管问题中有所有指示):
<DllImport("test.dll", CallingConvention:=CallingConvention.Cdecl)> _
Public Shared Function AddNumbers(ByVal a As Integer, ByVal b As Integer, _
ByRef result As Integer)
End Function
Public Function AddNumbers_Wrapper(ByVal a As Integer, _
ByVal b As Integer) As Integer
Dim result As Integer
AddNumbers(a, b, result)
Return result
End Function
确保根据非托管方法的调用约定正确设置DllImport 属性的CallingConvention 字段。
Here's a more detailed tutorial 了解如何在 Microsoft 网站上开始使用 P/Invoke。
【讨论】: