如何在C++中使用CUPS获取网络打印机?cupsGetDests需传入http_t*变量
CUPS cupsGetDests 参数问题解决方案
问题根源:CUPS版本API差异
CUPS 2.0 是关键版本分界线:
- CUPS 1.x 版本:
cupsGetDests()的签名为int cupsGetDests(cups_dest_t **dests),无需传入http_t*参数,你找到的代码就是针对该版本编写的。 - CUPS 2.x 及以上版本:API签名更新为
int cupsGetDests(http_t *http, cups_dest_t **dests),必须传入CUPS服务器的连接句柄http_t*。
对应解决方案
情况1:使用CUPS 1.x 或需兼容旧版本
直接使用你找到的代码,但需补充资源释放逻辑(避免内存泄漏):
#include "assets/cups/cups.h" #include <iostream> void list_printers(){ cups_dest_t* dests; int num_dests = cupsGetDests(&dests); for(int i=0; i<num_dests; i++){ std::cout << dests[i].name << std::endl; } // 必须释放打印机列表资源 cupsFreeDests(num_dests, dests); }
情况2:使用CUPS 2.x 及以上版本
需要先建立到CUPS服务器的连接,再调用新版API,示例代码如下:
#include "assets/cups/cups.h" #include <iostream> void list_printers(){ // 建立到本地CUPS服务器的默认连接(端口631,自动处理加密) http_t *http = httpConnectEncrypt("localhost", ippPort(), cupsEncryption()); if (!http) { std::cerr << "无法连接到CUPS服务器" << std::endl; return; } cups_dest_t* dests; int num_dests = cupsGetDests(http, &dests); for(int i=0; i<num_dests; i++){ std::cout << dests[i].name << std::endl; } // 释放资源:先释放打印机列表,再关闭连接 cupsFreeDests(num_dests, dests); httpClose(http); }
额外注意事项
- 编译时需链接CUPS库,命令示例:
g++ your_code.cpp -o printer_list -lcups - 确保本地CUPS服务处于运行状态(可通过访问
http://localhost:631验证) - 所有动态分配的资源(
dests、http连接)必须手动释放,避免内存泄漏
内容的提问来源于stack exchange,提问作者Tobias
相关产品推荐
相关产品推荐

