[ocaml-ctypes] string_of_char_ptr

john skaller skaller at internode.on.net
Sat Jan 20 23:36:33 GMT 2018


> On 21 Jan. 2018, at 10:17, Jeremy Yallop <yallop at gmail.com> wrote:
> 
> On 20 January 2018 at 22:08, john skaller <skaller at internode.on.net> wrote:
>> According to Real World Ocaml string_of_char_ptr can be used to convert a
>> C char* to an Ocaml string. But I can’t find it anywhere in the API!
>> 
>> Any clues?
> 
> I don't think that function is exposed in the API, at least in recent
> versions.  

It’s not, its in the repository in an *.ml file which is not exposed,
its used to define a view. One supplies read and write functions
to views, but is there a way to get them back?

The API is too abstract. I’d have used a concrete record :)


> But if you have a 'char ptr' value 'p' then you can convert
> it to a string using 'coerce':
> 
>     coerce (ptr char) string p
> 
> For example:
> 
>     # let getenv = foreign "getenv" (string @-> returning (ptr char));;
>     val getenv : string -> char Ctypes_static.ptr = <fun>
>     # let p = getenv "USER";;
>     val p : char Ctypes_static.ptr = (char*) 0x7ffe712cd9f8
>     # coerce (ptr char) string p;;
>     - : string = “jeremy"

Ouch. That doesn’t make sense. I mean I’m happy that it will do the 
job, thanks for the info! But that’s not what a C programmer would
think of as a coercion. Pointers and what they point at are distinct.

Sigh .. of course now I am binding a function that returns a char* and
of course the docs don’t say who owns the storage. Is it in a static
buffer? Part of another data structure? Malloc()’d and therefore
I have to free it? The usual problem with C: the fuctional API
is weakly specified and the resource management isn’t specified at all ;)
Off to troll the *.c files to see how its implemented… argghhh…



—
john skaller
skaller at users.sourceforge.net
http://felix-lang.org



More information about the Ctypes mailing list