[英]How can I call C++ functions from within ruby
I am an experienced C/C++ developer but I am a novice in Ruby. 我是一位经验丰富的C / C ++开发人员,但我是Ruby的新手。
How can I call a C++ function from with in Ruby? 如何在Ruby中调用C ++函数?
You have 3 possibilities : 你有3种可能性:
1) Ruby is able to load libraries. 1)Ruby能够加载库。 Even if it is a bit tricky, you can decide to write your own loader and bind your C++ library in Ruby. 即使它有点棘手,您也可以决定编写自己的加载器并在Ruby中绑定C ++库。 This is done using what is called an extension module . 这是使用所谓的扩展模块完成的 。 You will find a comprehensive tutorial here: http://www.rubyinside.com/how-to-create-a-ruby-extension-in-c-in-under-5-minutes-100.html 你会在这里找到一个全面的教程: http : //www.rubyinside.com/how-to-create-a-ruby-extension-in-c-in-under-5-minutes-100.html
2) You can use a tool that will generate the Ruby wrapper around your C++ library. 2)您可以使用一个工具来生成围绕C ++库的Ruby包装器。 Look at SWIG for example ( http://www.swig.org/ ). 以SWIG为例( http://www.swig.org/ )。 You just have to create a file in a swig-specific syntax and provide it to SWIG. 您只需使用特定于swig的语法创建文件并将其提供给SWIG。 It will then be able to generate the wrapper for many languages, Ruby included. 然后它将能够为包含Ruby的许多语言生成包装器。
3) You can choose to use a middleware , such as CORBA/ICE/whatever. 3)您可以选择使用中间件 ,例如CORBA / ICE /等等。 It may be a bit overkill if you only want to call some C++ functions, but it will allow you to remote call the functions, or "hide" a grid behind the middleware. 如果你只想调用一些C ++函数,它可能有点矫枉过正,但它允许你远程调用函数,或“隐藏”中间件后面的网格。
To call C++ code from Ruby, you will likely want to build an extension. 要从Ruby调用C ++代码,您可能希望构建扩展。
If you are an experienced C++ developer, you may feel comfortable with Rice: 如果您是一位经验丰富的C ++开发人员,您可能会对Rice感到满意:
https://github.com/jasonroelofs/rice https://github.com/jasonroelofs/rice
It uses C++ metaprogramming techniques to simplify writing extensions. 它使用C ++元编程技术来简化编写扩展。
If you were calling into C, you could also use ffi. 如果你打电话给C,你也可以使用ffi。 Calling C++ code is a little more complicated than calling C code due to name mangling and exceptions. 由于名称修改和异常,调用C ++代码比调用C代码要复杂一些。
I believe the questioner is asking how to call C++ from with in Ruby, if so then the for simple C/C++ RubyInline 1 is by the far the simplest solution. 我相信提问者正在询问如何在Ruby中调用C ++,如果是这样,那么简单的C / C ++ RubyInline 1是迄今为止最简单的解决方案。
Alternatively if you need to call more substatntial C++ code, you can build a ruby extension. 或者,如果您需要调用更多的基本C ++代码,则可以构建ruby扩展。 Here is a good tutorial 这是一个很好的教程
You need to wrap your c++ code in a C interface and then bind those C functions to ruby methods using rb_define_method() 您需要将C ++代码包装在C接口中,然后使用rb_define_method()将这些C函数绑定到ruby方法
alternatively you can use SWIG, as Aurelien said. 或者你可以使用SWIG,正如Aurelien所说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.