C++在 Ruby C 扩展中,指针问题

C++ in Ruby C extensions, pointer problems

本文关键字:指针 问题 扩展 Ruby C++      更新时间:2023-10-16

我正在尝试构建一个使用一些c ++库的Ruby C扩展。 问题是我什至无法让一个简单的"hello world"工作。

//hello_world.cpp
#include <ruby.h>

static VALUE tosCore;
static VALUE my_function( VALUE self )
{
    VALUE str = rb_str_new2( "Hello World!" );
    return str;
}
extern "C"
void Init_hello_world( void )
{    
    tosCore = rb_define_module("Core");
    rb_define_module_function(tosCore, "my_method", my_function, 0);   
}

我得到的输出是

compiling hello_world.cpp
hello_world.cpp: In function 'void Init_hello_world()':
hello_world.cpp:17:67: error: invalid conversion from 'VALUE (*)(VALUE) {aka lon
g unsigned int (*)(long unsigned int)}' to 'VALUE (*)(...) {aka long unsigned in
t (*)(...)}' [-fpermissive]
In file included from c:/Ruby200/include/ruby-2.0.0/ruby.h:33:0,
                 from hello_world.cpp:2:
c:/Ruby200/include/ruby-2.0.0/ruby/ruby.h:1291:6: error:   initializing argument
 3 of 'void rb_define_module_function(VALUE, const char*, VALUE (*)(...), int)'
[-fpermissive]
make: *** [hello_world.o] Error 1

我不是C/C++专家。 Ruby 是我的语言。 我已经在 Rice 下编译了几千行C++没有问题,但由于我希望这个特定的扩展在 Windows 下编译,所以 Rice 不是一个选择。

这是因为您向rb_define_module_function提供的函数回调不是编译器所期望的。它想要一个看起来像这样的函数:

VALUE my_function(...)

但是你的功能是

VALUE my_function( VALUE self )

请注意参数列表中的差异。

消除错误的一种方法是将参数类型转换为rb_define_module_function期望的类型:

rb_define_module_function(tosCore, "my_method",
    reinterpret_cast<VALUE(*)(...)>(my_function), 0);

您可以在此处阅读有关reinterpret_cast的信息。