使用codeblocks用C语言编程生成动态链接库(DLL),代码主要包含三类函数:入参整型,返回整型;入参浮点,返回指针数组;入参指针数组,返回浮点。
使用codeblocks编写C程序不在此赘述,此处直接附代码!
#include <stdio.h> #include <stdlib.h> int add1(int a, int b);//入参整型,返回整形; float *add2(float a, float b);//入参浮点,返回指针数组; float add3(float *arr);//入参指针数组,返回浮点 int main() { int a,b,c; a = 2; b = 3; c = add1(a,b); printf("1 无指针函数:\t\t%d\n",c); float *c2 = add2(a,b); printf("2 函数返回数组:\t%f\n",*(c2+1)); float result; float arr[] = {1.1,2.2}; result = add3(arr); printf("3 输入参数为数组:\t%f\n",result); system("pause"); return 0; } int add1(int a, int b) { int c; c = a + b; return c; } float *add2(float a, float b) { static float c[2]; c[0] = a + b; c[1] = c[0] + 1; return c; } float add3(float *arr) { float c; c = arr[0] + arr[1]; return c; }确认编写的C程序中函数可以顺利运行,下附运行结果。
2.1.1【codeblocks】File->New->Projects->Dynamic Link library->Go 2.1.2给项目命名为:fordll(可以自定义) 2.1.3修改项目中的main.cpp和main.h,此处附代码。
//main.cpp #include <stdio.h> #include <stdlib.h> #include <string.h> #include "main.h"//勿忘!!! int add1(int a, int b) { int c; c = a + b; return c; } float *add2(float a, float b) { static float c[2]; c[0] = a + b; c[1] = c[0] + 1; return c; } float add3(float *arr) { float c; c = arr[0] + arr[1]; return c; } //main.h #ifndef MAIN_H_INCLUDED #define MIAN_H_INCLUDED #ifdef __cplusplus #define EXPORT extern "C" __declspec (dllexport) #else #define EXPORT __declspec (dllexport) #endif // __cplusplus #include <windows.h> EXPORT int add1(int a, int b); EXPORT float *add2(float a, float b); EXPORT float add3(float *arr); #endif // MAIN_H_INCLUDED编译完成后找到该project的的目录文件,打开fordll/bin/Debug 这时可以看到生成的libfordll.a 、 fordll.dll 、libfordll.def文件。
3.1.1创建win32项目:File->New->Projects->Win32 GUI project->Go 3.1.2给项目命名为:testdll(可以自定义) 3.1.3修改项目中的main.cpp,然后再添加一个main.h文件,并把上面main.h中的代码复制到现在这个main.h中,此处附代码。
//main.h #ifndef MAIN_H_INCLUDED #define MIAN_H_INCLUDED #ifdef __cplusplus #define EXPORT extern "C" __declspec (dllexport) #else #define EXPORT __declspec (dllexport) #endif // __cplusplus #include <windows.h> EXPORT int add1(int a, int b); EXPORT float *add2(float a, float b); EXPORT float add3(float *arr); #endif // MAIN_H_INCLUDED //main.cpp,整体与Step1中类似,但不需要函数定义 #include <windows.h>//此处与Step1中不同 #include <stdio.h> #include <stdlib.h> #include "main.h"//勿忘!!! int main() { int a,b,c; a = 1; b = 6; c = add1(a,b); printf("1 无指针函数:\t\t%d\n",c); float *c2 = add2(a,b); printf("2 函数返回数组:\t%f\n",*(c2+1)); float result; float arr[] = {1.1,3.2}; result = add3(arr); printf("3 输入参数为数组:\t%f\n",result); system("pause"); return 0; }3.2.1添加Step2.2生成的libfordll.a库文件 选择菜单Settings->Compiler->Linker settings->Add 添加libfordll.a库文件。 3.2.2将Step2.2生成的fordll.dll库文件复制到Step3生成的project的bin/Debug目录下。 3.2.3配置完成后即可build-run;后续随时打开上图中exe文件都可得到下图运行结果。
[1] 用codeblocks中创建和调用动态链接库(dll) 如有侵权,请发送邮件至lxiong13@outlook.com联系我!Merci beaucoup!
