CWrap - higher abstraction level for calling C functions

Denis Shelomovskij verylonglogin.reg at gmail.com
Mon Feb 20 06:02:49 PST 2012


D has complete (IMHO) compiler support for calling C functions (using 
extern(C)). But there is a lack of library support. Microsoft .NET 
Framework has such support, but it's poor (see previous thread about 
CWrap in digitalmars.D NG).

Once original function is properly described in IDL, CWrap gives the 
fallowing advantages:
* [memory-corruption-safe] User works with arrays, not separate pointers 
and lengths.
* [memory-leak-safe] Original function allocated memory will be freed on 
any failure (NOTE: see "Original function restrictions" in documentation).
* [fail-safe] An exception will be thrown if original function fails.
* [usability] Much easier to work with arrays/preferred string types (it 
converts UTF-8/16/32 back and forth, see docs).
* [speed] No unnecessary GC (or other) allocations/copying/reading.
* [garbage-free] Look at, e.g. std.file - it leaves lots of garbage 
because of calling native platform functions. Generated wrappers don't 
even allocate GC memory (except for output parameters when user do want 
get GC allocated buffers).

Sources: https://bitbucket.org/denis_sh/cwrap
Docs (incomplete): http://deoma-cmd.ru/d/docs/src/cwrap.html

Phobos is needed.
Besides Phobos, the only file needed for generating: cwrap.d
The only file needed for generated wrappers to work: internal/cwraprt.d

Library state: almost every internal function is unittested, generated 
wrappers pass rather complicated test-suit in internal/cwrapunittests.d

"Examples" is the most informative section of the documentation. Other 
examples:
1. Original functions, all in one file:
https://bitbucket.org/denis_sh/cwrap/src/tip/examples/c.d
https://bitbucket.org/denis_sh/cwrap/src/tip/internal/cwrapunittests.d
2. Generated wrappers:
https://bitbucket.org/denis_sh/cwrap/src/tip/out

NOTE1: You need dmd 2.058 to generate wrappers at CT.
NOTE2: You can change `enum data` to `auto data` in examples/c.d, this 
will reduce compilation time.

Previous thread about CWrap in digitalmars.D NG:
http://www.digitalmars.com/d/archives/digitalmars/D/Higher_abstraction_level_for_calling_C_functions_156633.html


More information about the Digitalmars-d-announce mailing list