Thursday, December 11, 2008

PLT-Scheme Foreign Functions Tip

I'm my spare time, I'm still kicking around the idea of integrating PLT-Scheme and Tcl/Tk. While poking around looking for more foreign function interface examples, I came upon a fix to in issue I ran into last time I was playing around.

The problem is this: when I imported the foreign.ss library, I lost the ability to describe function contracts. That is, I can't do:

#lang scheme
(require scheme/foreign)
(unsafe!)

(define c-string-length 
  (get-ffi-obj "strlen" #f (_fun _string -> _int)))

(provide/contract
 [c-string-length (-> string? string?)]))

That's because the -> is a conflict - it's used by both the contract and foreign libraries.

Luckily, I stumbled on this example here, which elegantly solves this problem. See:

#lang scheme
(require scheme/foreign
         (rename-in scheme/contract [-> -->]))
(unsafe!)

(define c-string-length 
  (get-ffi-obj "strlen" #f (_fun _string -> _int)))

(provide/contract
 [c-string-length (--> string? string?)])

I forget that the module system let's you play games like this to fix import conflicts. It's also a good reminder that while contracts feel like they are built in, they're just like any other library you can import.

Speaking of foreign function Tcl/Tk interfaces, I have to say I'm impressed with Tkx. This Perl module has a clever means of passing Perl callbacks to Tcl code. It also has some conventions that make it easy to write Perl looking code, yet have it translate seamlessly into Tcl. I'm thinking of it as inspiration.

No comments:

Post a Comment