C语言调用api

一、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调用关键点

  1. 头文件包含

    • Windows: <windows.h>

    • Linux: 对应头文件如<sys/types.h><unistd.h>

  2. 函数声明

    • 需正确定义函数参数和返回类型

    • Windows API多使用__stdcall调用约定

  3. 链接库

    • Windows: 显式链接库(如-luser32-lgdi32

    • Linux: 一般自动链接标准库

  4. 错误处理

// 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

六、注意事项

  1. 调用约定:Windows API多使用WINAPI(__stdcall),普通C函数使用cdecl

  2. 类型匹配:注意Windows的DWORD、HANDLE等特殊类型

  3. 内存管理:某些API需要手动释放资源(如CloseHandle)

  4. 线程安全:注意API是否线程安全

  5. 版本兼容性:注意不同系统版本API的差异

建议在实际开发中:

  1. 查阅官方API文档

  2. 使用现代API替代已弃用的函数

  3. 考虑使用跨平台库(如Boost、Qt)

  4. 对系统相关代码进行条件编译

#ifdef _WIN32
    // Windows代码
#else
    // Linux代码
#endif

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值