求函数加入动态库及使用范例及说明。

解决方案 »

  1.   

    // File:  RUNTIME.C
    // A simple program that uses LoadLibrary and 
    // GetProcAddress to access myPuts from MYPUTS.DLL. 
     
    #include <stdio.h> 
    #include <windows.h> 
     
    typedef VOID (*MYPROC)(LPTSTR); 
     
    VOID main(VOID) 

        HINSTANCE hinstLib; 
        MYPROC ProcAdd; 
        BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 
     
        // Get a handle to the DLL module.
        //加载了一个叫myputs的dll 
        hinstLib = LoadLibrary("myputs"); 
     
        // If the handle is valid, try to get the function address.
     
        if (hinstLib != NULL) 
        { 
            //获取该dll中的函数地址
            ProcAdd = (MYPROC) GetProcAddress(hinstLib, "myPuts"); 
     
            // If the function address is valid, call the function.
     
            if (NULL != ProcAdd) 
            {
                fRunTimeLinkSuccess = TRUE;
                //开始调用
                (ProcAdd) ("message via DLL function\n"); 
            }
     
            // Free the DLL module.
            //一定free,否则内存泄漏!
            fFreeResult = FreeLibrary(hinstLib); 
        } 
     
        // If unable to call the DLL function, use an alternative.
     
        if (! fRunTimeLinkSuccess) 
            printf("message via alternative method\n"); 
    }
      

  2.   

    首先创建一个DLL工程,然后加入函数(求方根)进入DLL中:
    #include <math.h>
    extern "C" __declspec(dllexport) double Square(double d)
    { AFX_MANAGE_STATE(AfxGetStaticModuleState());
    TRACE("Entering Ex21cSquareRoot\n");
    if (d >= 0.0) {
    return sqrt(d);
    }
    AfxMessageBox("Can't take square root of a negative number.");
    return 0.0;
    }
    导入DLL时,首先申明一下:extern "C" __declspec(dllimport) double Square(double d);