简体   繁体   English

SWIG:从Python向C ++抛出异常

[英]SWIG: Throwing exceptions from Python to C++

We've got an interface we've defined in C++ (abstract class, all functions pure virtual) which will be extended in Python. 我们有一个用C ++定义的接口(抽象类,所有函数都是纯虚拟的),它将在Python中进行扩展。 To overcome the cross-language polymorphism issues we're planning on using SWIG directors . 为了克服跨语言多态性问题,我们计划使用SWIG Director I've read how to catch exceptions thrown from C++ code in our Python code here , here , here , and even on SO . 我已经在这里这里这里甚至在SO上阅读了如何捕获我们的Python代码中C ++代码引发的异常的信息。

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. 我想知道并且似乎无法在文档中找到的是如何使扩展的C ++接口的Python实现以使它们对C ++代码可见的方式抛出这些C ++异常。

We could make small functions within the *.i files such that each function throws our exceptions: 我们可以在* .i文件中制作一些小的函数,以便每个函数都抛出我们的异常:

void throw_myException(){ throw MyException; }

but I'm wondering how it will interact with the Python code. 但我想知道它将如何与Python代码进行交互。

Anyone have any experience with throwing C++ exceptions from Python code? 任何人都有从Python代码引发C ++异常的经验吗?

(C)Python is written in C. It seems that it could be bad to throw exceptions "through" the interpreter. (C)Python是用C编写的。“通过”解释器抛出异常似乎很糟糕。

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. 我的感觉是,从可以通过工厂创建异常的API返回某种令牌可能是最安全的。

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. 尽管我们使用C#而不是Python来生成“错误代码”数据,然后将其转换为C ++层,然后发送给异常工厂,但这基本上就是我们在这里所做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM