how to catch D Throwables (or exceptions) from C++?
Jacob Carlborg via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Dec 2 00:13:51 PST 2016
On 2016-12-01 02:58, Timothee Cour via Digitalmars-d-learn wrote:
> eg:
>
> ```
> dlib.d:
> extern(C) void dfun(){assert(0, "some_msg");}
>
> clib.cpp:
> extern "C" void dfun();
> void fun(){
> try{
> dfun();
> }
> catch(...){
> // works but how do i get "some_msg" thrown from D?
> }
> }
> ```
At least for a C++ exception it's possible to get the current exception
with __cxxabiv1::__cxa_current_primary_exception(). I verified and it
works for C++ exceptions. I would think that the following works for D
exceptions, but I cannot even catch the D exception in C++. Maybe it's
not working properly on macOS.
// c++
void foo();
const char* getExceptionMessage(void*);
void bar()
{
try
{
foo();
}
catch(...)
{
void* e = __cxxabiv1::__cxa_current_primary_exception();
if (e)
{
const char* msg = getExceptionMessage(e);
if (msg)
printf("%s\n", msg);
else
printf("no message\n");
}
else
{
printf("no exception\n");
}
}
}
// d
extern(C++) void foo()
{
throw new Exception("foo");
}
extern(C++) immutable(char)* getExceptionMessage(void* e)
{
if (e)
{
auto t = cast(Throwable) e;
return t.msg.ptr;
}
return null;
}
I'm compiling the C++ code with clang++ and I need to link with libc++abi.
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list