[ocaml-ctypes] Passing Caml function to C
john skaller
skaller at internode.on.net
Thu Dec 28 17:34:15 GMT 2017
> On 29 Dec. 2017, at 03:44, Jeremy Yallop <yallop at gmail.com> wrote:
>
> Serge Sivkov has explained how things work using OCaml's standard
> Callback module. Ctypes provides a slightly different mechanism.
> The implementation of funptr uses the closure functions in the libffi
> library to dynamically generate function pointers
>
> http://www.chiark.greenend.org.uk/doc/libffi-dev/html/The-Closure-API.html
The standard way to do that is
THUNK:
JSR handler
DATA data_address
DATA code_address’
and you just pop the return address off the stack to get the
data and code addresses, leaving the return address of the call to THUNK.
But the thunk has to be in memory which is both writable and executable,
and usually that combination is disallowed for ordinary users for
security reasons. Hmmm.
In my system I use the
void *client_data
pointer that callbacks, and the HOFs that accept them, almost always
have. However, the programmer has to TELL the compiler which
argument is the client data pointer.
This doesn’t require any thunks, but it doesn’t work without a client data pointer.
An amusing story .. except for those that had to deal with this massive
screw up .. in older versions of Windows, the event callbacks were passed
the window handle. So you would store the client data in the window data
frame. There was only one problem: when you created a window,
your callback had to PUT the client data pointer into the window frame.
The problem was .. where did you GET that client data from, in a callback?
So what you did was put it into a global variable and hope and pray that
the very next callback was the create window callback so it picked
up the right data from the global variable.
MS fixed it with CreateWindowEx.
—
john skaller
skaller at users.sourceforge.net
http://felix-lang.org
More information about the Ctypes
mailing list