[C language] 3. Dynamic link library generation and calling

Dynamic link library generation

My host environment is as follows:

  • Operating system: Windows 10
  • IDE:Clion
  • Compiler: MinGW

The following are the steps to generate the link library:

  • 1. Create a new project, select New C Library, and select the typeshared
    insert image description here

  • 2. Write a function to calculate the area of ​​a circle and calculate the circumference of a circle

#include "library.h"

#include <stdio.h>

#define PI 3.1415926

double GetCircleArea(float r){
    
    
    return PI * r * r;
}

double GetCircleLength(float r){
    
    
    return PI * r * 2;
}

3. Compile into a dll file
insert image description here

  • 4. cmake-build-debugA callable dll dynamic link library file will be generated in the directory

Dynamic link library calls

The following is the code to call the dynamic link library file just generated:

#include <stdio.h>
#include<Windows.h>

int main() {
    
    
    HMODULE h = NULL;//创建一个句柄h
    h = LoadLibrary("libtestdll.dll");
    if (h == NULL)//检测是否加载dll成功
    {
    
    
        printf("加载libtestdll.dll动态库失败\n");
        return -1;
    }
    typedef double (*GetArea)(float); // 定义函数指针类型
    typedef double (*GetLength)(float); // 定义函数指针类型
    GetArea getArea;
    GetArea getLength;
    getArea = (GetArea) GetProcAddress(h,"GetCircleArea");
    getLength = (GetLength) GetProcAddress(h,"GetCircleLength");
    float r;
    printf("请输入圆的半径:\n");
    scanf("%f",&r);
    printf("圆面积为:%f\n",getArea(r));
    printf("圆周长为:%f\n",getLength(r));

    return 0;
}

Note: libtest.dllI put the file in the execution directory, so the file path written is actually a relative path

Guess you like

Origin blog.csdn.net/m0_56963884/article/details/129302699