[gambit-list] c++ example

Marc Feeley feeley at iro.umontreal.ca
Wed Nov 24 15:14:09 EST 2010


On 2010-11-24, at 2:05 PM, David Dreisigmeyer wrote:

> Does anyone have a simple example of calling a C++ function from
> Gambit?  Thanks, -Dave

Calling C++ functions is just like calling C functions (see the Gambit manual for examples).

If you want to call C++ methods, below you'll find an example of calling some C++ fstream methods.  I even threw in the automatic reclaiming of the C++ allocated ofstream object.

Marc


(c-declare #<<c-declare-end

#include <fstream>

___SCMOBJ delete_ofstream(void *ptr)
{
  delete (std::ofstream*)ptr;
  return ___NO_ERR;
}

c-declare-end
)

(c-define-type std::ofstream "std::ofstream")
(c-define-type std::ofstream*
               (pointer std::ofstream (std::ofstream*)))
(c-define-type std::ofstream*/GC
               (pointer std::ofstream (std::ofstream*) "delete_ofstream"))

(define new-ofstream
  (c-lambda (nonnull-char-string) std::ofstream*/GC
            "___result_voidstar = new std::ofstream(___arg1);"))

(define ofstream-write-string
  (c-lambda (std::ofstream* nonnull-char-string) void
            "*___arg1 << ___arg2;"))

(define ofstream-close
  (c-lambda (std::ofstream*) void
            "___arg1->close();"))

;; test:

(let ((s (new-ofstream "bar")))
  (pretty-print s)
  (ofstream-write-string s "hello!\n")
  (ofstream-close s))




More information about the Gambit-list mailing list