Reputation:
I used Microsoft Visual Studio 2008 to create a C# application, and now I want to use a C-based DLL.
How can I add a reference to that C-based DLL to my C# application in Visual Studio 2008?
Upvotes: 1
Views: 233
Reputation: 244971
You cannot add a reference to a native (unmanaged) DLL in either a C# or VB.NET project. That is simply not supported. References only work for other managed DLLs (i.e., those you might write in C# or VB.NET, or even C++/CLI).
However, you can still make use of the code in that DLL. The trick is to call the functions it provides dynamically at runtime using the same P/Invoke syntax that you use to call functions from the Win32 API.
For example, assume you have the following code compiled into a DLL using C++:
extern "C" {
__declspec(dllexport) void AddNumbers(int a, int b, int* result)
{
*result = (a + b);
}
}
Now, assuming that you compiled that DLL to a file named test.dll
, you could call that function by adding the following code to your C# application:
[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;
}
Or in VB.NET, since you're apparently using that (despite all indications in the question):
<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
Make sure that you set the CallingConvention
field of the DllImport
attribute appropriately, depending on the calling convention of your unmanaged method.
Here's a more detailed tutorial on how to get started with P/Invoke on Microsoft's site.
Upvotes: 4