C#呼叫C++DLL

☆綠茶☆發表於2013-07-14

extern "C" __declspec(dllexportint 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);

 

http://blog.csdn.net/procedurecode/article/details/2244419

相關文章