Last active
September 29, 2016 19:31
-
-
Save kugel-/364fa0011f18f83583f5400f49f6f386 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
cc $(pkg-config --cflags --libs-only-L ruby-2.3) -Wl,-export-dynamic test.c -o test $(pkg-config --libs ruby-2.3) | |
*/ | |
#include <stdio.h> | |
#include <dlfcn.h> | |
#include <ruby.h> | |
const char script[] = | |
"require 'rubygems'\n" | |
"require 'ffi'\n" | |
"module LibWrap\n" | |
" extend FFI::Library\n" | |
" ffi_lib [FFI::CURRENT_PROCESS, '']\n" | |
" callback :completion_function, [:string, :long, :uint8], :void\n" | |
" attach_function :do_work, [:pointer, :completion_function], :int\n" | |
" Callback = Proc.new do |buf_ptr, count, code|\n" | |
" puts(\"ruby says #{buf_ptr}\")\n" | |
" end\n" | |
"end\n" | |
"\n" | |
"LibWrap.do_work(\"test\", LibWrap::Callback)\n"; | |
typedef void completion_function(char *buffer, long count, unsigned char code); | |
extern int do_work(char *buffer, completion_function *); | |
static completion_function *ruby_func; | |
int do_work(char *buffer, completion_function *fn) | |
{ | |
/* Calling fn directly here works */ | |
ruby_func = fn; | |
return 0; | |
} | |
int main() | |
{ | |
int state = 0; | |
VALUE ret; | |
/* construct the VM */ | |
ruby_init(); | |
ruby_init_loadpath(); | |
rb_eval_string_protect(script, &state); | |
if (state) | |
{ | |
VALUE e = rb_errinfo(); | |
ret = rb_funcall(e, rb_intern("message"), 0); | |
fprintf(stderr, "exc %s\n", StringValueCStr(ret)); | |
rb_set_errinfo(Qnil); | |
} | |
else | |
{ | |
/* Calling fn here hangs, because ffi expects an initial ruby stack frame */ | |
ruby_func("hello", 5, 0); | |
} | |
/* destruct the VM */ | |
return ruby_cleanup(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment