Calling C code from within Ruby — How to use the returned pointer?

后端 未结 1 554
猫巷女王i
猫巷女王i 2021-01-05 13:03

Problem:

I\'d like to use in my Ruby program an algorithm that is coded in C and exposed through a DLL.

I would like to treat the algorithm

相关标签:
1条回答
  • 2021-01-05 13:11

    While I don't know why the Win32API approach did not work, I've found an easier solution using FFI to the problem of calling C functions from within Ruby or interfacing with DLLs.


    Solution using FFI

    Use FFI in Ruby for interfacing with DLLs, as follows:

    • (1) Install ffi (works with ruby 1.9.3, ymmv with previous versions)

      gem install ffi

    • (2) Create your own Ruby module to wrap the C function

    require 'ffi'
    
    module CodeGen                   # Ruby wrapper  (your choice)
      extend FFI::Library
      ffi_lib 'codegen'              # DLL name  (given)
      attach_function 
            :create_code,            # method name  (your choice)
            :CreateCodeShort3,       # DLL function name (given)
              [ :int, :string, :string, :uint, :ushort, :ushort], :string  
                              # specify C param / return value types 
    end
    
    ret_str = CodeGen.create_code(3, "foo", "bar", 0,0,0)
    
    puts ret_str
    
    • (3) Run. Result gives a string as desired.

    Done!

    0 讨论(0)
提交回复
热议问题