For Platform calls to unmanaged functions, the minimum requirement is Dllimport Property to include DLL . DLL Can be DLL Absolute path of, such Dllimport (@ "D:" bookcode "nativelib. dll ") . Or yes. DLL For example Dllimport ("nativelib. dll ") . When it is specified as a relative path, CLR Searches for this unmanaged instance in the following search path. DLL . First, CLR This unmanaged directory will be searched in the current directory DLL . If it is not found, it will turn to search Windows System directory. If not found Path Search all directories listed by environment variables. If this is not found in all the directories listed above DLL , CLR Will throw Dllnotfoundexception . It can be seen that if the unmanaged function to be called is not in all available paths, it cannot be called on the platform.
By carefully analyzing the platform call process and principles, you can intuitively come up with a dynamic platform call method. That is, inDLLBefore calling the platform, that isCLRStart searching for unmanaged Resources in the default search pathDLLAnd useWin32 API loadlibraryLoad thisDLLPreviously, it was manually usedLoadlibraryTo load unmanaged dataDLL. This wayCLRYou can find this unmanagedDLLAnd Platform calls for the specified unmanaged functions.
Class dynamicpinvokevialoadlib
{
[Dllimport ("nativelibfordynamicpinvoke. dll")]
Static extern int multiply (INT factora, int factorb );
Public static void test ()
{
String currentdirectory =
Path. getdirectoryname (assembly. getexecutingassembly (). Location );
String dllpath = path. Combine (currentdirectory,
@ "Nativelibfordynamicpinvoke" nativelibfordynamicpinvoke. dll ");
Intptr dlladdr = WIN32API. loadlibrary (dllpath );
If (dlladdr = intptr. Zero)
{
Throw new dllnotfoundexception (
String. Format ("can not load {0}, please check.", dllpath ));
}
//Call an unmanaged Function
Int factora = 100, factorb = 8;
Int result = multiply (factora, factorb );
//Print results
Console. writeline (string. Format ("{0} * {1} = {2}", factora, factorb, result ));
Console. writeline ("press any key to exit .");
Console. Read ();
}
}
WhereLoadlibraryYesWIN32APIClassWin32 APIFunction, which is defined as follows:
[Dllimport ("kernel32.dll", entrypoint = "loadlibrary")]
Public static extern intptr loadlibrary (
String lplibfilename
);
As beforeCodeDeclare the unmanaged functions to be called and add themDllimportAttribute. InDllimportProperty to includeDLLWhen using a relative path, onlyDLL. Because of thisDLLNot inCLRUnder the default search pathCLRIt cannot be searched and usedLoadlibraryTo load it. The solution to this problem isDLLBefore calling the platform, manually useLoadlibraryTo load unmanaged dataDLL. The bold Section in the above Code demonstrates this method.
RunDynamicpinvokevialoadlibClassTestThe following result is displayed:
100*8 = 800 Press any key to exit. |
To be continued ......