Polymorphism across C++ and Ruby using SWIG

不羁岁月 提交于 2019-12-04 15:11:30

I got a solution to my problem from Tobias Grimm at the swig-user mailing list. The first part of the problem is SWIG's misleading error message. The message seems to suggest that I pass the wrong type of pointer to my C++ function, but this is not the case. If you check the class of the exception in Ruby, it's ObjectPreviouslyDeleted, meaning that the underlying C struct pointer of my Cat class is NULL. So the real problem is that the pointer is NULL, not that it has the wrong type.

The pointer is NULL because I simply forgot to call "super" in Cat's initialize() method. This way, with the creation of Cat no underlying C struct gets allocated, because the Animal constructor never gets called. Forgetting to call 'super' is a very common Ruby-beginner's mistake, especially for people like me who come from C++, who are used to automatic constructor chaining.

So all I had to do was add a call to 'super':

class Cat < Animal   # Inherit from a C++ class
   def initialize
      puts "Creating new cat"
      super()
   end
   def sound
      puts "Meow"
   end
end

This now works fine. Thanks, Tobias.

I believe you need to define a helper function that returns a pointer to your instance. I have only used pointers with fopen, so I don't know if this will really work, or if there is something else I am missing. Good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!