Using <c-string> with FFI calls

Home
Introduction
Tips and Techniques
Projects
Libraries
Links

The following relates to Functional Developer and Harlequin Dylan.

The Dylan type <c-string> allows you to efficiently deal with data received from external API's written in the C programming language (or languages that use the C style zero terminated strings).

If you have a pointer to a zero terminated string as a result of an FFI call you can convert this to a Dylan <c-string> without doing any copying of the data. The internals of the <c-string> type will point directly to the memory location of the zero terminated string. Here is an example:

   let buffer = api-call-returning-pointer();
   make(<c-string>, 
        address: buffer.pointer-address);

If the string you require from the API call is at a different location in the buffer than offset zero you can use pointer addition with something like the following:

   let buffer = api-call-returning-pointer();
   make(<c-string>, 
        address: \%+(buffer.pointer-address, 100));

If you want to copy a string from a Dylan <string> to a buffer obtained from an FFI call you can use the copy-bytes! function. This is much faster than iterating over the Dylan <string> and assigning the characters individually:

   let buffer = api-call-returning-pointer();
   let dylan-string = "Hello World";
   with-c-string(source = dylan-string)
     copy-bytes!(buffer, source, source.size + 1);
   end with-c-string;

Copyright © 2000, Chris Double. All Rights Reserved.
All products and brand names are the registered trademarks or trademarks of their respective owners.