complex number types in mixing C(99) and C++
I'm writing a math library, the core of it is in C++. Later it may be implemented in pure C (C99 I suppose). I think I need a C like API so that I can get Python and matlab and the like to use the library. My impression is that doing this with C++ is painful.
So is there a good or standard or proper way to cast between double compl开发者_开发问答ex *some_array_in_C99
, and complex<double> *some_array_in_cpp
?
I could just use void *
pointers, but I'm not sure if that's good.
This may be nitpicking, because ctypes seems to work fine with complex<double>
, but I'm worried about matlab and other possible numerical environments.
The C99 and C++0x standards both specify that their respective double complex types must have the same alignment and layout as an array of two doubles. This means that you can get away with passing arguments as a void *
and have your routines be (relatively) easily callable from either language, and this is an approach that many libraries have taken.
The C++0x standard guarantees (§26.4) that a reinterpret_cast
of std::complex<double>*
to double*
will do the right thing; if I remember correctly, this was not so clearly specified in earlier versions of the standard. If you are willing to target C++0x, it may be possible for you to use this to do something cleaner for your interfaces.
Given that the actual layout and alignment specifications are defined to agree, I would be tempted to just condition the type in the header file on the language; your implementation can use either language, and the data will be laid out properly in memory either way. I'm not sure how MATLAB does things internally though, so I don't know if this is compatible with MATLAB or not; if they use the standard LAPACK approach, then it will be on many but not all platforms in all circumstances; LAPACK defines its own double complex
type to be a struct
with two double
members, which will usually be laid out the same way in memory (this isn't guaranteed), but could follow a different calling convention on some platforms.
精彩评论