Function pointer with Ruby/DL

  • Thread starter Guillaume Marcais
  • Start date
G

Guillaume Marcais

Yet another question about this amazing library.

How can I call a pointer to a function. Let say:

<code>
int my_function(void);
int (*function_hook)(void);
function_hook = my_function;
</code>

Can I call the function pointed to by function_hook?

Guillaume.
 
T

Takaaki Tateishi

Guillaume said:
How can I call a pointer to a function. Let say:

<code>
int my_function(void);
int (*function_hook)(void);
function_hook = my_function;
</code>

If the function_hook is globally defined variable, I mean it should be
exported, the address
of function_hook is obtained as follows.

module MyLib
extend DL::Importable
dlload "foo.so"

HOOK_ADDR = symbol "function_hook"
end

and use Symbol.new to construct function call as follows:

def call_function_hook()
sym = DL::Symbol.new(MyLib::HOOK_ADDR.ptr, "function_hook", "I")
result = sym.call
return result[0]
end

the following foo.c and foo.rb are samples..

foo.c --
int my_function(){
return 20;
}

int (*function_hook)();

void define_hook(){
function_hook = &my_function;
}

foo.rb --
require 'dl/import'

module MyLib
extend DL::Importable
dlload "foo.so"

extern "void define_hook()"

HOOK_ADDR = symbol "function_hook"
def call_function_hook()
sym = DL::Symbol.new(HOOK_ADDR.ptr, "function_hook", "I")
result = sym.call
result[0]
end
module_function :call_function_hook
end

#MyLib.define_hook()
p MyLib.call_function_hook()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,901
Members
47,439
Latest member
elif2sghost

Latest Threads

Top