From: Robert Feldt Date: 2003-09-24T15:01:26+09:00 Subject: Re: A DL-Ruby Question Kevin Proctor skrev den Wed, 24 Sep 2003 13:57:58 +0900: > But, and there's always a but, you may have noticed the ugliness in my sqlite_exec function. I'm just passing an int (0 specifically) - I really want to put a 'function pointer' there to do neat things with the results of my sql statement. For the life of me I can not find an example of doing something like this in DL. I'm sure it's there somewhere but I'm stumped. > If you're trying to do a callback to Ruby from C then this example might help you: # Example 7. Calling back to a Ruby function from a C function # # Sometimes C code takes a function as a parameter and calls that function. # To be able to use such C code from Ruby we need to be able to call back # from C to Ruby and transfer parameters and results back and forth. # Here's a simple example to show how this can be done. # require 'example_runner' cf = CFile.new "ex1.c", < /* CompareStringLengths is a pointer to a function comparing the length * of two strings and returning -1, 0, or 1 */ typedef int (*CompareStringLengths)(char *str1, char *str2); extern void report_string_compare(char *str1, char *str2, CompareStringLengths compare_func) { int result = (*compare_func)(str1, str2); printf("Results was %d.\\n", result); } EOC cf.compile_to_dll_with_command "gcc -shared -o test.so" require 'dl/import' require 'dl/struct' module Ex07 extend DL::Importable dlload './test.so' def str_len_compare(str1, str2) puts "Callback succeeded: We are in Ruby from C now!" str1.length <=> str2.length end STRLENCOMPARE = callback "int str_len_compare(char*,char*)" extern "void report_string_compare(char*, char*, void*)" end Ex07.report_string_compare("ab", "cde", Ex07::STRLENCOMPARE) Ex07.report_string_compare("abc", "d", Ex07::STRLENCOMPARE) Ex07.report_string_compare("ab", "cd", Ex07::STRLENCOMPARE) I did a series of such examples and intended to release them but then I got stuck on the non-portability of nested structs and didn't go further in my efforts to use dl for a full extension. The example_runner is just a little class to compile the C code to a dll; excluded here for brevity. Regards, Robert Feldt