Скажем, у нас есть класс C++
Код: Выделить всё
class myCppClass
{
public:
myCppClass(){}
virtual std::vector compute_things();
};
Код: Выделить всё
%module(package="example", directors="1", allprotected="1", "threads"=1) My_Example
%{
#include
}
%import
%include
%include
%import "numpy.i"
%feature("director") myCppClass;
%include
Код: Выделить всё
class myPythonClass(myCppClass):
def __init__(self):
super().__init__()
def compute_things(self):
return np.array([2.0, 1.0])
myclass = myPythonClass()
myclass.compute_things()
Если я возвращаю int или a дважды все идет хорошо.
Я поместил несколько инструкций по обработке ошибок в файл .i, но ни одна из них не активирована.
Код: Выделить всё
%feature("director:except") {
if ($error != NULL) {
PyErr_Print();
if (PyErr_GivenExceptionMatches($error, PyExc_TypeError)) {
throw std::invalid_argument("director:except TypeError");
}
else {
throw Swig::DirectorMethodException("Unknown exception thrown by Python SWIG director method");
}
}
}
%exception{
try { $action }
catch (std::invalid_argument& exc) {
if (std::string(exc.what()) == "director:except TypeError") {
SWIG_exception_fail(SWIG_TypeError, "TypeError exception thrown by Python SWIG director method");
}
else {
std::string message = std::string("Exception '") + std::string(exc.what()) + "' thrown by C++ function : $fulldecl";
SWIG_exception_fail(SWIG_ValueError, message.c_str());
}
}
catch (Swig::DirectorMethodException& exc) {
SWIG_exception_fail(SWIG_UnknownError, exc.what());
}
catch (Swig::DirectorException &e) { SWIG_fail; }
catch (...) {
SWIG_exception_fail(SWIG_UnknownError, "Unknown exception thrown by C++ function : $fulldecl");
}
}
%include "exception.i"
%exception
{
try
{
$action
}
catch (const std::runtime_error& e) {
SWIG_exception(SWIG_RuntimeError, e.what());
}
catch (const std::invalid_argument& e) {
SWIG_exception(SWIG_ValueError, e.what());
}
catch (const std::out_of_range& e) {
SWIG_exception(SWIG_IndexError, e.what());
}
catch (...) {
SWIG_exception(SWIG_RuntimeError, "unknown exception");
}
}
Большое спасибо за помощь.
Подробнее здесь: https://stackoverflow.com/questions/792 ... ctordouble
Мобильная версия