Parameter transfer for dynamic calling of unmanaged DLL in Asp.net
Author: proud cat
Source: http://blog.csdn.net/shardowm
Recently, due to work reasons, I encountered the problem of calling the unmanaged DLL parameter transfer in Asp.net. It took me half a day to finally solve the problem perfectly. I hereby write this article to share with you. Here we will mainly explain the problem of parameter passing when calling the DLL. There are many articles on how to call the unmanaged DLL online, which will not be repeated here.
Libinvoke calls an unmanaged DLL in the Asp.net environment. In the class, the invoke method creates the delegate object of the method specified in the DLL.
Public class libinvoke
...{
...
Public Delegate invoke (string apiname, type T)
...{
If (hlib = intptr. Zero)
Throw (new exception ("A valid DLL module is not loaded. Check whether the DLL file" + strdll + "is valid! "));
Intptr Hapi = intptr. zero;
HAPI = getprocaddress (hlib, apiname );
If (Hapi = intptr. Zero)
Throw (new exception ("invalid function name:" + apiname ));
Return marshal. getdelegateforfunctionpointer (HAPI, t );
}
}
I. built-in types
It is the easiest to PASS Parameters of built-in types (integer, Boolean, and numeric). You only need to directly pass the parameters and directly process the returned values.
Private delegate bool func1 (int A, char B );
Public bool basetypetest
...{
Func1 fun = (func1) objinvoke. Invoke ("basetypetest", typeof (func1 ));
Bool res = fun (1, 'A ');
Return res
}
Ii. string type
When a string is passed in, due to the character string encoding problem, it may cause the character string to become garbled in the DLL, so here we will convert the strings into byte arrays, then, it is passed into the DLL function as a parameter.
Private delegate bool func2 (byte [] _ appid, byte [] _ paramval );
Public bool stringtypetest1 (string appid, string paramvalue)
...{
Encoding e1 = encoding. getencoding (936 );
Byte [] b1 = e1.getbytes (appid );
Byte [] b2 = e1.getbytes (paramvalue );
Func2 func = (func2) objinvoke. Invoke ("stringtypetest1", typeof (func2 ));
Bool result = func (b1, b2 );
Return result;
}
If a string is to be returned in the DLL, the returned string can only be used as a reference parameter of the function, but cannot be directly returned by the function. The following code calls
Void stringtypetest2 (char **)
Function.
Private delegate void func3 (Out stringbuilder RET );
Public String stringtypetest2
...{
Stringbuilder OBJ = new stringbuilder ();
Func3 func = (_ author) objinvoke. Invoke ("stringtypetest2", typeof (func3 ));
Func (Out OBJ );
Return obj. tostring ();
}
Therefore, it should be noted that the function that returns the string or object type should not allow the function to directly return the string or object, but should use the string or object to be returned as a reference parameter.
References:
[1] Jason clark,
Web: http://www.microsoft.com/china/msdn/library/langtool/vcsharp/ousNET.mspx