跳到主要內容

發表文章

目前顯示的是有「boost」標籤的文章

Exception Translation from C++ to Python with Boost.Python

Exception Translation from C++ to Python with Boost.Python Scenario Say we have written a Python binding with Boost.Python. Something like following code. // some.cpp # include <stdexcept> # include <boost/python.hpp> struct my_exception : std :: exception { my_exception ( int extra_info ) : extra_info ( extra_info ) { } char const * what ( ) noexcept ( true ) { return "My exception" ; } int const extra_info ; } ; void do_throw ( ) { throw my_exception ( ) ; } // Something should be done here ... BOOST_PYTHON_MODULE ( MyLib ) { using namespace boost :: python ; def ( "do_throw" , & do_throw ) ; } And we wish to catch a Python exception object in Python code, e.g. import MyLib try : MyLib . do_throw ( ) except MyLib . MyException as e : print e , e . extra_info pass The situation is, we can’t directly pass the exception object, my_exception,...

boost::python - 從 C C++ 中呼叫 Python 函式

boost::python - 從 C C++ 中呼叫 Python 函式 背景 如果對 callback 已經很熟悉的可以跳過這段;不少函式庫的 API 會接收 callback 或者是 action 函式,如下 // File: callback.hpp # ifndef CALLBACK_HPP_ # define CALLBACK_HPP_ // void* 為使用者傳入的 context, val 是函式庫指定的值 typedef void ( raw_cb_t ) ( void * ctx , int val ) ; void libfunc ( raw_cb_t * cb , void * ctx ) ; # endif 這裡的 raw_cb_t cb 就是 callback/action 函式,作為一個參數傳遞給 libfunc ,由它決定何時呼叫,如下 // File: callback.cpp # include "callback.hpp" void libfunc ( raw_cb_t * cb , void * ctx ) { for ( int i = 0 ; i < 10 ; i ++ ) { cb ( ctx , i ) ; } } 使用 libfunc 這個 API 的方式在 C/C++ 裡面可以是 // File: main.cpp # include <iostream> # include "callback.hpp" void handler ( void * ctx , int val ) { int * sum = static_cast < int * > ( ctx ) ; std : : cout << ( * sum ) + = val << std : : endl ; } int main ( void ) { int sum = 0 ; libfunc ( & handler , ...