处理共享库中的策略错误 - C [英] Error handling strategies in a shared library - C

查看:147
本文介绍了处理共享库中的策略错误 - C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C编写一个跨平台共享库( .so 在linux和 .dll 中)目前当有错误时,库函数返回正确的错误代码,并将错误信息写入 stderr 。库函数还会发送一些信息并将消息调试到 stdout 。这适用于基于控制台的客户端。

I am writing a cross platform shared library (.so in linux and .dll in windows) using C. Currently when there is a error, library functions returns the proper error code and writes error information into the stderr. Library functions also emits some information and debug messages to stdout. This works well for console based clients.

现在这个库将有使用GUI编程的客户端程序,使用C ++& wxWidgets的。我想知道处理错误的最佳做法是什么? UI应用程序可以访问所有平台上的 stdout stderr 的数据吗?

Now this library will have client programs that uses GUI programmed using C++ & wxWidgets. I am wondering what would be the best practices in handling the errors and notifying it? Can a UI application access data coming to stdout and stderr on all platforms?

我想到的另一种方法是库初始化函数初始化一个将具有函数指针的结构。库上的所有函数都将使用此结构的一个实例并调用函数指针。这样客户端可以选择打印消息的位置。

An alternative way I was thinking is the library initialization function initializes a structure which will have function pointers. All the functions on the library will take an instance of this structure and call the function pointers. This way the client can choose where to print the messages.

我想知道解决这个问题的明显方法是什么?任何帮助都会很好。

I am wondering what would be the obvious way to solve this? Any help would be great.

推荐答案

最佳实践(IMHO)是一个图书馆不打印任何东西到stderr(或stdout)因为他们甚至可能不存在。除了GUI情况,您还可以使用没有控制台的服务器应用程序的用例,并且可能希望使用syslog()等功能记录错误。

Best practice (IMHO) is for a library to not print anything to stderr (or stdout), because they may not even be present. In addition to the GUI situation, you also have the use case of a server application that doesn't have a "console", and may want to be logging errors using a function like syslog().

一些处理错误信息而不直接打印的方法:

Some approaches for handling error information without printing it directly:


  • 返回数字错误代码,提供将其转换为字符串的功能

  • return a numeric error code, and provide a function for turning it into a string

返回一个结构/对象错误代码,其中包含其他信息

return a struct/object error code, which contains additional information

在会话对象上提供一个返回关于最后一个错误的信息的函数

provide a function on a "session" object that returns info about the last error

允许调用者注册被调用的回调发生错误

allow the caller to register a callback that's invoked in the event of an error

不要从库中写入stderr规则的一个例外我相当舒服的是如果一个库有一个调试模式参数,可以将详细的信息记录到stderr。

The one exception to the "don't write to stderr from a library" rule that I'm reasonably comfortable with is if a library has a "debug mode" parameter that enables logging of detailed info to stderr.

这篇关于处理共享库中的策略错误 - C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆