[ocaml-ctypes] Help with strings

john skaller skaller at internode.on.net
Mon Dec 25 21:44:57 GMT 2017


Hi!

I have not been able to understand well enough how the
memory management protocols work.

In C, there is a problem that pointed at objects, especially char*
and char** are used as parameters and return values but the
type does not specify ownership. This has to be done in comments.

The method of binding is different. For example

	char const *get_version();
	char *get_buffer();
	char *strdup(char *);


The first function returns a pointer to an immutable global object.
The second to a mutable part of a buffer.
The third to a freshly malloc()ed copy of a NTBS.

Also, strdup is accepting a string argument which it does not own
so the caller must free it if the caller allocated it. The return value
belongs to the caller so must be freed.

Obviously “returning string” Ctypes spec is not going to work for
all three of these return types and it isn’t clear how “string”
works for the strdup argument. The string would be invisible to
the Ocaml caller, so how does it get freed? Ctypes can’t know
when to free it. 

Here’s another example:

	memcpy (a,b,n)

which returns a copy of b, the output buffer pointer. And another

	void add_opt (char **, char*)

which adds the second argument to an array of NTBS (terminated
by a NULL pointer).

C types had better not delete the argument char* it creates for a string
argument, but on the other hand, the client CANNOT delete it because
it is hidden. Either we get a crash or a leak.

So roughly, if you wanted to do it right, Ctypes “type” system is inadequate.
The “types” must contain mutablility and ownership information.
For example

	immutable_lend_noincrementable_nonnull_pointer_char


is better, but STILL not enough to ensure that a char const * passed to
a function can be freed after Ctypes creates a copy of the Ocaml string
contents (because the candidate function could return the pointer).

Basically the programmer has to tell Ctypes the access method of
every (non-scalar) object. 

Of course I can do that by passing a char ptr manually created
(C types can do that I think), copying Ocaml string contents manually
(how?), and then manually free-ing it (C types can do that?)

So roughly .. when is it safe to use “string”?
At the moment the answer for me is “never” because I don’t understand the
memory management protocol.


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



More information about the Ctypes mailing list