一、Windows平台调用Win32 API
#include <windows.h>
int main() {
// 调用MessageBox API
MessageBox(
NULL, // 窗口句柄
"Hello, Windows API!", // 文本内容
"API示例", // 标题
MB_OK | MB_ICONINFORMATION // 按钮和图标
);
return 0;
}
编译命令:
gcc -o demo demo.c -luser32
二、Linux系统调用(文件操作)
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd = open("demo.txt", O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
// 错误处理
return 1;
}
const char* text = "Hello, Linux System Call!";
write(fd, text, strlen(text));
close(fd);
return 0;
}
编译命令:
gcc -o demo demo.c
三、通用API调用关键点
-
头文件包含
-
Windows:
<windows.h>
-
Linux: 对应头文件如
<sys/types.h>
,<unistd.h>
-
-
函数声明
-
需正确定义函数参数和返回类型
-
Windows API多使用
__stdcall
调用约定
-
-
链接库
-
Windows: 显式链接库(如
-luser32
,-lgdi32
) -
Linux: 一般自动链接标准库
-
-
错误处理
// Windows错误处理示例
if (!SomeWindowsAPI()) {
DWORD err = GetLastError();
// 处理错误
}
// Linux错误处理示例
if (some_syscall() == -1) {
perror("Error occurred");
// 处理错误
}
四、动态库调用示例(Windows DLL)
#include <windows.h>
typedef int (*AddFunc)(int, int);
int main() {
HINSTANCE hDll = LoadLibrary("math.dll");
if (hDll) {
AddFunc add = (AddFunc)GetProcAddress(hDll, "add");
if (add) {
int result = add(5, 3);
printf("5 + 3 = %d\n", result);
}
FreeLibrary(hDll);
}
return 0;
}
五、跨平台库调用(以libcurl为例)
#include <curl/curl.h>
int main() {
CURL *curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
CURLcode res = curl_easy_perform(curl);
if(res != CURLE_OK)
fprintf(stderr, "curl failed: %s\n", curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
return 0;
}
编译需要链接curl库:
gcc -o demo demo.c -lcurl
六、注意事项
-
调用约定:Windows API多使用
WINAPI
(__stdcall),普通C函数使用cdecl
-
类型匹配:注意Windows的DWORD、HANDLE等特殊类型
-
内存管理:某些API需要手动释放资源(如CloseHandle)
-
线程安全:注意API是否线程安全
-
版本兼容性:注意不同系统版本API的差异
建议在实际开发中:
-
查阅官方API文档
-
使用现代API替代已弃用的函数
-
考虑使用跨平台库(如Boost、Qt)
-
对系统相关代码进行条件编译
#ifdef _WIN32
// Windows代码
#else
// Linux代码
#endif