我建议使用 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