简体   繁体   English

使用SWIG将Ruby嵌入C ++应用程序中?

[英]Embedding Ruby in a C++ application using SWIG?

I've successfully created Ruby-C++ bindings in the past using SWIG where the C++ code was compiled as a dynamic library with the Ruby script connecting to it. 过去,我已经使用SWIG成功创建了Ruby-C ++绑定,其中C ++代码通过连接到Ruby脚本的形式编译为动态库。

However, I'd like to do it the other way around. 但是,我想反过来做。 Create an executable using C++ and enable it to load and execute Ruby code. 使用C ++创建可执行文件,并使其能够加载和执行Ruby代码。 Ruby should be able to call functions defined on the C++ side as well (naturally, otherwise all I would need is the 'system()' call.) Ruby也应该能够调用在C ++端定义的函数(自然,否则,我所需要的只是'system()'调用。)

Does SWIG provide the means to achieve this? SWIG是否提供实现此目标的方法?

您可能对C ++中嵌入的Ruby感兴趣

SWIG solves part of your problem: it lets you create Ruby bindings to C++ functions that you've written. SWIG解决了部分问题:它使您可以创建与已编写的C ++函数的Ruby绑定。 The other half of your problem, making a C++ program that can evaluate Ruby code, can be as easy or complicated as you wish. 问题的另一半,就是制作一个可以评估Ruby代码的C ++程序,它可以像您希望的那样简单或复杂。

The easy way is to divide your program into two halves: a ruby-accessible part that lives in a dll, and an inaccessible part that links with that dll and invokes Ruby via system() . 一种简单的方法是将程序分为两半:位于dll中的红宝石可访问部分,以及与该dll链接并通过system()调用Ruby的不可访问部分。

At a slightly higher level, you can use ruby's C API from C++ to run Ruby code. 在更高的层次上,您可以使用C ++中的ruby的C API来运行Ruby代码。 This gives you better control over how Ruby code is executed, and offers you the opportunity to do things like wrap all executed Ruby in blocks that generate C++ exceptions from Ruby exceptions. 这使您可以更好地控制Ruby代码的执行方式,并有机会进行诸如将所有已执行的Ruby包装在从Ruby异常生成C ++异常的块中的操作。 The downside here is that you will need to understand Ruby's C API, which is not awful but certainly isn't as friendly as, say, Lua's. 这里的缺点是您需要了解Ruby的C API,虽然它并不糟糕,但肯定不如Lua的友好。

If you want more than that, you're into deep waters. 如果您还想要更多,那么您将陷入困境。 Ruby and C++ are both complicated languages, and getting them to interoperate is a real challenge. Ruby和C ++都是复杂的语言,要使它们互操作是一个真正的挑战。 Éric Malenfant's link may be of some use to you. ÉricMalenfant的链接可能对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM