Skip to content

ftype-pointer and foreign-procedure: counter-intuitive behavior #270

Open
@stergiotis

Description

@stergiotis

Consider the following example program:

(import (chezscheme))
(load-shared-object "libc.so.6")
(define memcpy/void* (foreign-procedure "memcpy" (void* void* size_t) void*))

(define sz (ftype-sizeof uptr))
(define a-addr (foreign-alloc sz))
(define b-addr (foreign-alloc sz))
(define a (make-ftype-pointer uptr a-addr))
(define b (make-ftype-pointer uptr b-addr))

(ftype-set! uptr () a #xdeadbeef)
(memcpy/void* b-addr a-addr sz)
(pretty-print (number->string (ftype-ref uptr () b) 16))

(foreign-free a-addr)
(foreign-free b-addr)

It works but is very weakly typed as we supply fixnums as argument for the foreign function: Supplying a-addr and b-addr instead of a and b circumvents the type checks. To strengthen the checks I expected that all of the following three variations are valid. They are however rejected as invalid.

;; 1) declare memcpy with typed pointers to be able to use ftype-pointer
(define memcpy/uptr* (foreign-procedure "memcpy" (uptr* uptr* size_t) void*)) ;; --> exception: invalid foreign-procedure argument type specifier uptr*
(memcpy/uptr* b a sz)

;; 2) rely on C rule that a typed pointer will be down-cast to void*
(memcpy/void* b a sz) ;; --> Exception in memcpy/void*: invalid foreign-procedure argument #<ftype-pointer uptr 94627085533504>

;; 3) make a void* ftype-pointer
(memcpy/void* (make-ftype-pointer void b-addr)
              (make-ftype-pointer void a-addr)) ;; --> Exception: unrecognized ftype name void

In my opinion this would be a valuable addition to the beautiful Chez ftype interface.

  1. Would be neat as it would allow to declare pointer to pointers correctly. Currently only base types do seem to be supported.
  2. Is a bit of a hack as it mimics the behavior of C but not that of C++.
  3. Seems to be quite nice as it allows to explicitly cast any pointer to void* which is a useful and proven idiom.

Any thoughts on this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions