From: Todd Fisher Date: 2008-07-24T11:24:46+09:00 Subject: Re: calling c++ from Ruby Mr_Tibs wrote: > Hi, > > I wrote this question on the newsgroup yesterday, but I didn't see it > actually get posted. Here it goes again. I'm trying to call a c++ > function from Ruby and I'm getting some errors compiling the c++ > part. > > Here is my code: > #include "ruby.h" > #include > #include > VALUE MyTest = Qnil; > extern "C" VALUE create_project(char *c, ...) > { > va_list args; > va_start(args, c); > } > extern "C" void Init_mytest() > { > MyTest = rb_define_module("MyTest"); > rb_define_method(MyTest, "create_project", &create_project, > 1); > } > > And here is the error: > MyTest.cpp: In function �void Init_mytest()�: > MyTest.cpp:16: error: invalid conversion from �VALUE (*)(char*, ...)� > to �VALUE (*)(...)� > MyTest.cpp:16: error: initializing argument 3 of �void > rb_define_method(VALUE, const char*, VALUE (*)(...), int)� > > If I don't put "char *c" in the arguments of create_project, it > compiles and works just fine. But if I don't have it, how can I get > the arguments? > I realize this is more of a c++ question, but if anyone has any > simple, fully working example of calling c++ code from Ruby, I would > like to see it. > > Thanks, > Tiberiu Hi, I think you meant to use rb_define_singleton_method, instead of rb_define_method. Also, the method signature of your C/C++ function is important. If you want to use variable number of arguments, it needs to look something like this: VALUE your_method_name(int argc, VALUE *argv, VALUE klass) Also, when using C++ you need to cast to correct types... so, in your case you could fix the compile time error by casting: rb_define_method(MyTest, "create_project", (VALUE (*)(...))&create_project, -1); Also, when using variable arguments you need to pass a -1, since it's an unknown number of arguments. Ruby also has it's own set of methods to use to access the arguments. Have a look at rb_scan_args, http://www.oreillynet.com/ruby/blog/2007/04/c_extension_authors_use_rb_sca_1.html Hope this helps, -Todd -- Posted via http://www.ruby-forum.com/.