C#动态调用C++DLL

1.DLL中函数实现

extern "C" __declspec(dllexport) int MultiplyByTen(int numberToMultiply);

extrn "C" _declspec(dllexport) int GenReg(char* id1, char *id2,char* string);

#include "DynamicDLLToCall.h"

int MultiplyByTen(int numberToMultiply)
{
        int returnValue = numberToMultiply * 10;
        return returnValue;
}
 

int GenReg(char* id1, char *id2,char* string)

{

   return 0;

}

2.导入DLL声明     

    #region P/Invoke helpers

   [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

   [DllImport("kernel32.dll")]
   public static extern bool FreeLibrary(IntPtr hModule);

  #endregion

  private delegate int MultiplyByTen(int numberToMultiply);

  
  private delegate int GenRegProc(byte[] id1, byte[] id2, byte[] string);

3.调用DLL

    IntPtr pDll = LoadLibrary("YourDll.DLL");

   IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, "MultiplyByTen");

   MultiplyByTen multiplyByTen = (MultiplyByTen)Marshal.GetDelegateForFunctionPointer(
                                                                                        pAddressOfFunctionToCall,
                                                                                        typeof(MultiplyByTen));

   IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, "GenReg");

  GenRegProc GenRegMethod = (GenRegProc)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall,typeof(GenRegProc));

   int regCode = GenRegMethod(Encoding.ASCII.GetBytes(device), Encoding.ASCII.GetBytes(productCode), Encoding.ASCII.GetBytes(CodeGenerator.GeneratorKey)).ToString();


    int theResult = multiplyByTen(10);    bool result = FreeLibrary(pDll);

 

你可能感兴趣的:(c++,c#,string,dll,byte,c)