SWIG:从 Python 向 C 抛出异常
我们已经在 C++ 中定义了一个接口(抽象类,所有函数都是纯虚拟的),它将在 Python 中扩展。为了克服跨语言多态性问题,我们计划使用 SWIG 控制器。我在 Python 代码这里阅读了如何捕获从 C++ 代码抛出的异常< /a>,此处,此处,甚至在SO。
这是相当简单的,我预计在处理我们图书馆自己的异常时不会出现问题。我想知道但在文档中似乎找不到的是如何让扩展 C++ 接口的 Python 实现以一种使 C++ 代码可见的方式抛出这些 C++ 异常。
我们可以在 *.i 文件中创建小函数,以便每个函数都会抛出异常:
void throw_myException(){ throw MyException; }
但我想知道它将如何与 Python 代码交互。
有人有从 Python 代码中抛出 C++ 异常的经验吗?
We've got an interface we've defined in C++ (abstract class, all functions pure virtual) which will be extended in Python. To overcome the cross-language polymorphism issues we're planning on using SWIG directors. I've read how to catch exceptions thrown from C++ code in our Python code here, here, here, and even on SO.
It's fairly straight forward and I'm not expecting issues with handling our library's own exceptions. What I'd like to know and can't seem to find in the documentation is how to have our Python implementation of the extended C++ interface throw those C++ exceptions in a way that makes them visible to the C++ code.
We could make small functions within the *.i files such that each function throws our exceptions:
void throw_myException(){ throw MyException; }
but I'm wondering how it will interact with the Python code.
Anyone have any experience with throwing C++ exceptions from Python code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(C)Python 是用 C 编写的。“通过”解释器抛出异常似乎可能很糟糕。
我的感觉是,从 API 返回某种可以通过工厂创建异常的令牌可能是最安全的。
这基本上就是我们在这里所做的,尽管我们使用 C# 而不是 Python 来生成“错误代码”数据,然后将其转换为 C++ 层,然后发送到异常工厂。
(C)Python is written in C. It seems that it could be bad to throw exceptions "through" the interpreter.
My feeling is that it's probably safest to return a token of some sort from your API that can create an exception via a factory.
That's basically what we do here, although we're using C# instead of Python to generate the "error code" data which then gets translated to the C++ layer and then sent off to the exception factory.