What is the proper way to link to functions in a C# DLL from a C# application?
This is how my DLL looks:
namespace WMIQuery_Namespace
{
public class WMIQuery
{
public static string GetPortName()
{
/* Does some stuff returning valid port name. */
return string.Empty;
}
public static int ScanForAdapters()
{
/* Does some stuff returning valid adapter index. */
return _index = -1;
}
}
}
This is how the interface in my application looks:
namespace MyApp_Namespace
{
class MyApp_Class
{
internal static class WMIQuery
{
[DllImport("WMIQuery.dll")]
internal static extern string GetPortName();
[DllImport("WMIQuery.dll")]
internal static extern int ScanForAdapters();
}
}
}
Everything compiles without any errors or warnings, but when I try to call these functions from my application this exception is thrown:
“Unable to find an entry point named
‘ScanForAdapters’ in DLL
‘WMIQuery.dll’.”
What am I doing wrong? I am aware that I can add WMIQuery as a reference, but I need to link it as an unmanaged DLL. Thanks.
If the DLL is a C# DLL, you don’t use P/Invoke to “link” to it.
Just add it as a reference to your project, and add, at the top of the class where you want to use it:
You can then directly do:
No need for any code in the “client” side at all…
As for:
Realize that the assembly will not be loaded until the point in time that your application uses it. Assemblies in the CLR are not loaded at startup, but rather at the time the first type is used from within the assembly. There is no need to try to load it via P/Invoke in order to achieve late binding.
If you don’t trust this, you can always use Assembly.Load and reflection to call the members, but Platform Invocation services will not work for loading a C# assembly.