Subject:
Re: [ruby-ffi] Re: My first example failed, can anyone help me?
From:
win kiwi
Date:
5/4/12 9:43 PM
To:
ruby-ffi@googlegroups.com

Thank you very much. It works now. But this is little weird. 
Before add extern "C", I also write a C code to test the shared library. It works well.

2012/5/3 Wayne Meissner <wmeissner@gmail.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.