Subject:
[ruby-ffi] Re: My first example failed, can anyone help me?
From:
Wayne Meissner
Date:
5/3/12 5:02 AM
To:
ruby-ffi@googlegroups.com

You need to declare the native function as 'extern "C"'

e.g.

extern "C" void hello();



On Thursday, May 3, 2012 6:43:45 PM UTC+10, win kiwi wrote:
I write a c header file:

hello.h
-------------------------------
extern void hello();
-------------------------------

souce file: hello.cpp
------------------------------
#include "hello.h"
#include <stdio.h>

void hello() {
        printf("hello");
}
------------------------------

I use this command to generate .so in ubuntu:

g++ -O -fpic -shared -o hello.so hello.cpp


Now, the hello.so is under my directory.

I write a ruby file: helloLib.rb:
-----------------------------
require 'ffi'
module HelloLib
        extend FFI::Library
        ffi_lib File.dirname(__FILE__) + "/hello.so"
        attach_function :hello, [], :void
end
----------------------------

then, I write codes to call this wrapper

hellotest.rb
-------------------------------
require 'rubygems'
require 'ffi'
require 'helloLib'

HelloLib.hello()
-------------------------------

I type : ruby ./hellotest.rb at the console . get following error
information:


/var/lib/gems/1.8/gems/ffi-1.0.11/lib/ffi/library.rb:249:in
`attach_function': Function 'hello' not found in [./hello.so]
(FFI::NotFoundError)
        from ./helloLib.rb:5
        from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in
`gem_original_require'
        from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from ./hellotest.rb:3


Can any one give me suggestion? Thank you.