[Haskell-cafe] C++ interface with Haskell

Isaac Dupree isaacdupree at charter.net
Sat Apr 19 09:45:22 EDT 2008

Evan Laforge wrote:
> To threadjack a little bit, I've been interfacing haskell with c++.
> It gets awkward when the c++ structures use STL types like string and
> vector.  Of course those are too complex for haskell to marshal to.
> What I've been doing is defining an XMarshal variant of the X c++
> class, that uses plain c arrays.  Then I marshal to that, and
> construct the c++ object properly from XMarshal in the c->c++ wrapper
> layer.  On a few occasions, when the c++ class is really big and only
> has one STL member, I make a partially constructed c++ object, pass
> the array separately, and then construct the proper c++ class from the
> broken haskell generated one.  Possibly dangerous as all get-out
> because I'm dealing with "unconstructed" c++ objects, but it seems to
> work.

you mean, you hack around with the internal representation of those 
structures?  Well, if you want to avoid double-copying, C++ can't access 
Haskell sequences, and Haskell can't access C++ sequences, I guess I 
don't see an alternative.

> Passing back to haskell is easier since I can use "&*vec.begin()",
> which according to the internet should be safe because STL guarantees
> that vector contents are contiguous.

safe until either:
the vector's contents change, if Haskell is assuming it's immutable,

or more seriously, if the vector's length is changed, the pointers are 
invalidated and it might crash (due to reallocating for a bigger 
continuous memory chunk)

> I'm only saved by the fact that I don't have that many different kinds
> of classes to pass.  This would be much more drudgery if I had more.
> Does anyone have a better solution or convention for marshalling c++
> objects?

not "better", but, you could wrap the methods of the class and call back 
into C++ (through C wrappers) to do anything with the class, if it 
suited your purposes better and wasn't too slow

> I've also noticed warnings from g++ about hsc2hs's use of the OFFSETOF
> macro on c++ classes, but some googling of g++ mailing lists implied
> that it's harmless if you don't have virtual bases, and what sane
> person does, so I suppress it now :)

More information about the Haskell-Cafe mailing list