Re: C-FFI, results, conditions
Thomas Chust <[email protected]>
| Newsgroups | gmane.comp.lang.dylan.gwydion.devel |
|---|---|
| Message-ID | <[email protected]> |
On Wed, 16 Jan 2013, Bruce Mitchener wrote:
> [...]
> When wrapping an API with C-FFI (either directly or via melange generating C-FFI), I often run into a situation where I have a function
> that returns 0 or an error code.
> I'd like to be able to have the C-FFI know how to pass the result to a mapping function which would check for non-zero and then signal a
> condition as appropriate.
> [...]
Hello,
if there are many functions returning the same type of result that needs
to be checked, wouldn't a C-mapped-subtype for the results make sense?
For all those C library functions that return positive integer handles or
a negative number to indicate failure I would probably write code like
this:
define C-variable C-errno :: <C-int>
c-name: "errno";
end;
define C-function C-strerror
parameter errno :: <C-int>;
result message :: <C-string>;
c-name: "strerror";
end;
define class <syscall-error> (<error>)
constant slot status :: <integer>, required-init-keyword: status:;
constant slot message :: <string>, init-keyword: message:, init-value: "Unknown error";
end;
define constant <nonnegative-integer> = limited(<integer>, min: 0);
define C-mapped-subtype <C-int-or-error> (<C-int>)
import-map <nonnegative-integer>, import-function:
method (result :: <integer>) => (checked :: <nonnegative-integer>)
if (result < 0)
let errno = C-errno();
error(make(<syscall-error>, status: errno, message: C-strerror(errno)));
else
result;
end;
end;
end;
define C-function C-open
parameter path :: <C-string>;
parameter flags :: <C-int>;
result handle :: <C-int-or-error>;
c-name: "open";
end;
...
I would probably also take an analogous route in SWIG and define a special
type map for these return values which would include the error handling
code.
If this solution sucks for some reason, my next idea would be to just
write a macro wrapping C-function-definer with additional syntactic sugar
for the generation of complex wrapper functions.
But it's been a while since I actually wrote something in Dylan, so I
wouldn't be surprised if my code didn't meet the style guidelines or if
there were much better solutions I overlooked ;-)
Ciao,
Thomas
--
When C++ is your hammer, every problem looks like your thumb.
_______________________________________________
hackers mailing list
[email protected]
https://lists.opendylan.org/mailman/listinfo/hackers