Hi
tldr; how do I “interface” (call functions, etc) with the outside from inside a Proc passed as a callback to a c function?
I am trying to use the wiringPi library in crystal on a raspberry pi and I have a problem with a function that requires a callback it has the following signature:
extern int wiringPiISR (int pin, int mode, void (*function)(void)) ;
What works so far is this:
module Wiringtest
@[Link("wiringPi")]
lib LibwiringPi
fun wiringPiSetupSys : Int32
fun wiringPiISR(pin : LibC::Int, edge_type : LibC::Int, f : Void -> Void) : LibC::Int
end
LibwiringPi.wiringPiSetupSys
f = -> ( x : Void ) { puts "test" }
LibwiringPi.wiringPiISR(13, 1, f )
end
loop do
sleep 1
end
This works, and when I push a button connected to the PI , it puts “test” on the console.
What I cannot get to work is calling any functions from the proc.
When I try I get the message that I cannot pass a closure to a c function, and the Documentation contains a chapter on how to deal with this, by “boxing” the proc and passing that as Data.
(Passing a closure to a C function )
The suggested method in the doc is to Box the proc and pass it in as “user value” and unbox it inside the proc. My problem is that that does not seem to apply in my case, because the C-function that takes the callback expects that the callback neither returns nor takes any values (void (*function)(void) )
Another suggested solution was a global variable (@@something in Module) and I can access that variable from inside the proc, but I did not manage to box some block in it to access it from inside the callback function.
again a suggestion from chat was to have a look at this:
crystal-chipmunk
_cp_gather point_query : PointQueryInfo,
def point_query(point : Vect, max_distance : Number = 0, filter : ShapeFilter = ShapeFilter::ALL, &block : PointQueryInfo ->)
LibCP.space_point_query(self, point, max_distance, filter, ->(shape, point, distance, gradient, data) {
data.as(typeof(block)*).value.call(PointQueryInfo.new(Shape[shape], point, distance, gradient))
}, pointerof(block))
end
And I have to admit this goes so far over my head it’s in danger of crashing into the ISS.
If anyone could help shed some light on the quote or the problem in general, I’d appreciate it very much.