How to use self-defined C++ extensions (.so) in Sketchup Ruby

Hi guys, I’m trying to use some self-defined C++ functions in Sketchup Ruby. I’ve already wrapped the C++ code into .so file outside Sketchup using SWIG. And it does work outside Sketchup, which means I can successfully use my C++ code in Ruby (not the Ruby console/editor inside Sketchup). However, when I tried to run the same Ruby code inside Sketchup using Ruby editor/console, it doesn’t work. It seems I cannot require the module defined in .so file. Here is the error information:

require “E:/Example”
Error: #<LoadError: 126: The specified module could not be found. - E:/Example.so>
C:/Program Files/SketchUp/SketchUp 2017/Tools/RubyStdLib/rubygems/core_ext/kernel_require.rb:54:in require' C:/Program Files/SketchUp/SketchUp 2017/Tools/RubyStdLib/rubygems/core_ext/kernel_require.rb:54:inrequire’

:in `' SketchUp:1:in `eval'

Does anyone know what’s the problem? Why the external-compiled module cannot be used in Sketchup Ruby? and how to solve this problem? My Sketchup version is 2017 with Ruby2.2.4. My laptop is Windows 10, and the Ruby program installed is Ruby2.1.9. Thank you very much.

It seems there’s a Ruby-c-extension tutorial. But I’m really confused about that because I’m new in C++ programming. I don’t really understand how to compile the code using SWIG in Visual Studio. Is that the only way to wrap and use self-defined c++ extension in Sketchup Ruby?

That’s also the Ruby version that you need to install and for which you need to compile your C++ code.

You can install multiple versions of Ruby with rvm (Ruby version manager), e.g. rvm use 2.2.4. This is a separate installation of Ruby and not connected in any way to the one in SketchUp, but you need it for compiling binaries with bindings to the Ruby C interface.

Problem solved! Thank you so much!! Yes, it is the Ruby version problem. The Ruby version inside and outside Sketchup should keep same if you’d like to wrap the c++ code in Ruby (the one outside Sketchup) and run the wrapped module in Sketchup Ruby.

rvm should be a very powerful tool to install Ruby. But I’m not familiar with that, so I just downloaded Ruby2.2.4 (the same version as in Sketchup 2017) from the historical Ruby archives and installed it on my laptop. Then I wrapped and compiled my c++ code using SWIG, and generate a shared library (.so file). This time I can successfully use this library in Sketchup Ruby. Hope this Q&A can help anyone else with the same problem. Thanks for your valuable answer Aerilius.

And if you also target other versions of SketchUp, you need to provide an .so file compiled for the corresponding Ruby version and load the right one in a Ruby loader script.

As a windows user since v1, I find uru (Unleash Ruby) much more familiar to use.

https://rubyinstaller.org/add-ons/uru.html

https://bitbucket.org/jonforums/uru