【问题标题】:access dll function on C project from Ruby从 Ruby 访问 C 项目上的 dll 函数
【发布时间】:2018-01-30 22:11:36
【问题描述】:

我有一个用 C 语言编写的控制硬件设备的项目。我正在尝试从 Ruby 应用程序访问我的项目中的 DLL 函数,以便从 Ruby Web 应用程序控制硬件。我无法使用 FFI 和 Fiddle 加载 dll 项目文件。有没有人可以分享一个类似案例的例子?

谢谢。

【问题讨论】:

  • 我建议看看这个swig.org
  • @shadowsheep SWIG 用于创建扩展,我希望将一个 dll 文件加载到我的 Ruby 应用程序中并使用其中的函数。我在这里错过了什么吗?
  • 不!您可以使用 swig 为您的 dll 自动生成 ruby​​ 包装器,就像 web.mit.edu/svn/src/swig-1.3.25/Examples/ruby/class/index.html
  • 请参阅教程swig.org/tutorial.html 抱歉,我没有用现场示例回答,因为现在我的手机上有。
  • 太酷了!好的谢谢! :)

标签: c ruby dll ffi fiddle


【解决方案1】:

我建议使用 SWIG (http://swig.org)

我会给你一个关于 OSX 的例子,但你也可以在 Windows 上找到等效的例子。

假设您有一个带有此头文件hello.h 的库(在我的情况下为 hello.bundle 或在您的情况下为 hello.DLL)

#ifndef __HELLO__
#define __HELLO__

extern void say_hello(void); 

#endif

你想从像 run.rb 这样的 ruby​​ 程序调用say_hello

# file: run.rb
require 'hello'

# Call a c function
Hello.say_hello

(注意这里模块名是大写的)

你要做的就是像这样创建一个文件hello.i

%module hello
 %{
 #include "hello.h"
 %}

 // Parse the original header file
 %include "hello.h"

然后运行命令:

swig -ruby hello.i

这将生成一个文件.c,它是一个包装器,将作为包装器模块安装在您的 ruby​​ 环境中:hello_wrap.c

那么你需要用这个内容创建一个文件extconf.rb

require 'mkmf'
create_makefile('hello')

注意这里的“hello”是我们模块在.i文件中的名称。

然后您必须运行ruby extconf.rb,它将生成一个 Makefile。

ruby extconf.rb    
creating Makefile

然后您必须键入make,它将针对库编译_wrap.c 文件(在我的情况下为.bundle 在您的情况下为.DLL)。

make
compiling hello_wrap.c
linking shared-object hello.bundle

现在您必须输入 make install(或 sudo make install 在 Unix/Osx 上)

sudo make install
Password:
/usr/bin/install -c -m 0755 hello.bundle /Library/Ruby/Site/2.3.0/universal-darwin17

然后你就可以运行你的程序run.rb

ruby run.rb 
Hello, world!

我将在此处粘贴.c 文件下方,用于生成库 hello.bundle

#include <stdio.h>
#include "hello.h"

void say_hello(void) {
    printf("Hello, world!\n");
    return;
}

如果您将此文件与 .h 文件一起保留,Makefile 将为您构建库

make
compiling hello.c
compiling hello_wrap.c
linking shared-object hello.bundle

【讨论】:

    猜你喜欢
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2022-01-22
    相关资源
    最近更新 更多