LoadLibraryA 和 GetProcAddress 調用動態庫

經過LoadLibraryA 和 GetProcAddress,動態調用無需配置連接庫lib和相關的頭文件配置。下面介紹一個例子的實現

 

一、動態庫ios

A、加法類windows

頭文件
#pragma
once class MyAdd { public: MyAdd(); virtual ~MyAdd(); int add(int a, int b); float add(float a, float b); }; 源文件: #include "MyAdd.h" MyAdd::MyAdd() { } MyAdd::~MyAdd() { }
int MyAdd::add(int a, int b) { return a + b; } float MyAdd::add(float a, float b) { return a + b; }

B、導出加法類接口api

 

頭文件:
#include <stdlib.h> #include "MyAdd.h" #include "add_api.h" int csvMyAddGetInstance(void ** ppHandle) { MyAdd* p = new MyAdd(); *ppHandle = p; return 0; } int csvMyAddReleaseInstance(void * ppHandle) { MyAdd* p = (MyAdd*)(ppHandle); if (p != NULL) { delete p; p = NULL; } return 0; } int csvMyAddaddInt(void ** ppHandle, int a, int b) { MyAdd* p = (MyAdd*)(ppHandle); if (p == NULL) return INT_MIN; return a + b; } float csvMyAddaddFloat(void ** ppHandle, float a, float b) { MyAdd* p = (MyAdd*)(ppHandle); if (p == NULL) return INT_MIN; return a + b; }

源文件:

#ifndef CSV_ADD_API_H

  #define CSV_ADD_API_H函數


  #ifdef CSVADDAPI_LIB
  #define CSVADDAPI_LIB_EXPORT extern "C" __declspec(dllexport)
  #else
  #define CSVADDAPI_LIB_EXPORT extern "C" __declspec(dllimport)
  #endifspa


  CSVADDAPI_LIB_EXPORT int csvMyAddGetInstance(void ** ppHandle);指針

  CSVADDAPI_LIB_EXPORT int csvMyAddReleaseInstance(void * ppHandle);code

  CSVADDAPI_LIB_EXPORT int csvMyAddaddInt(void ** ppHandle, int a, int b);blog

  CSVADDAPI_LIB_EXPORT float csvMyAddaddFloat(void ** ppHandle, float a, float b);接口

 
 

  #endif //CSV_ADD_API_Hip

 

 

 

二、調用動態庫

#include <iostream>
#include <stdlib.h>
#include <string>
#include<stdio.h>
#include <windows.h>
using namespace std;

/*經過LoadLibraryA 和 GetProcAddress,動態調用無需配置連接庫lib和相關的頭文件*/

typedef int(*MyAddGetInstance)(void **ppHandle);              //定義類型:獲取加法類的函數指針
typedef int(*MyAddReleaseInstance)(void *ppHandle);           //定義類型:聲明釋放加法類的函數指針
typedef int(*MyAddAddInt)(void **ppHandle, int a, int b);     //定義類型:聲明整數的加法函數指針

int main(int argc, char** argv)
{
    /*導入DLL庫*/ 
    string dll_path = "MyDll.dll";
    HINSTANCE phandle = LoadLibraryA(dll_path.c_str());

    /*獲取 DLL庫內部的函數句柄*/ 
    MyAddGetInstance csvMyAddGetInstance;
    csvMyAddGetInstance = (MyAddGetInstance)GetProcAddress(phandle, "csvMyAddGetInstance");
    MyAddReleaseInstance csvMyAddReleaseInstance;
    csvMyAddReleaseInstance = (MyAddReleaseInstance)GetProcAddress(phandle, "csvMyAddReleaseInstance");
    MyAddAddInt myAddAddInt;
    myAddAddInt = (MyAddAddInt)GetProcAddress(phandle, "csvMyAddaddInt");

    /*調用函數*/ 
    void* pinst = NULL;
    csvMyAddGetInstance(&pinst);    
    int res = myAddAddInt(&pinst, 1, 3);    
    csvMyAddReleaseInstance(pinst);

    cout << res << endl;

    system("pause");
    return  0;
}

 

源碼:源碼下載

相關文章
相關標籤/搜索