Dynamically call the method package of the function in the unmanaged MFC dynamic link library.

xiaoxiao2021-03-06  40

This is a method of encapsulating a dynamic link library function written by a non-hosting MFC. First, add the following namespace to the code to use reflection and metadata calls.

Using system.reflection.emit;

Using system.reflection;

Suppose we have a MFC Dynamic Link Library (GetMyversion.dll), where there is such a function INT GETDLVERSION (CHAR * VERSTR), which returns a function version string.

Methods will create a dynamic object set. Create a function with the DefinePinvokeMethod method, we will use the created function to access the DLL function we need. Tryed to CreateglobalFunctions for the global function. Call the function in the DLL with previously created GetMethod functions.

Public Object DynamicDllFunctionInvoke (String DLLPATH, STRING Entrypoint)

{

// Define the version number string byte [] VERSTR = New byte [1024];

/ / Define the return value type

TYPE RTURNTYPE = TypeOf (int);

/ / The input output parameter type of this method

TYPE [] ParameterTypes = {TypeOf (byte [])};

Object [] ParameterValues ​​= {VERSTR};

String EntryPoint = entrypoint;

// Create a dynamic code set and dynamic call module assemblyname asmname = new assemblyname ();

Asmname.name = "tempdll";

AskMBLYBUILDER DYNAMICASM =

Appdomain.currentDomain.defineDynamicassembly (asmname,

AskMBLYBUILDERACCESS.RUN);

ModuleBuilder DynamicMod =

Dynamicasm.defineDynamicModule ("TempModule");

// Use the input data dynamic to build a global call signature

Methodbuilder DynamicMethod = DynamicMod.definePinvokeMore (

Entrypoint, Dllpath, Methodattributes.Static | Methodattributes.public

| MethodAttributes.pinvokeImpl, Callingconventions.standard,

Returntype, ParameterTypes, CallingConvention.winapi,

Charset.ansi);

// Global method build

DynamicMod.createglobalFunctions ();

/ / Call information from the call method

MethodInfo Mi = DynamicMod.getMethod (entrypoint);

// Call the static method and return an Object type object

Object retval = mi.invoke (null, parametervalues);

MessageBox.show (System.Text.asciiencoding.ascii.getstring (VERSTR));

Return RetVal;

}

转载请注明原文地址:https://www.9cbs.com/read-66017.html

New Post(0)