红宝石 - 传递方法给DLL库作为回调 [英] Ruby - passing a method to a DLL library as a callback
问题描述
让我们说我有一个C / C ++库使用该功能,编译为一个DLL:
Let's say I have a C/C++ library with this function, compiled to a DLL:
#include <Windows.h>
extern "C" __declspec(dllexport) void __stdcall myFunction(void (*myCallback)(int)) {
int result = MessageBox(
0, (LPCWSTR)L"Press yes or no", (LPCWSTR)L"Test", MB_YESNO
);
myCallback(result);
}
这只是打开标准的Win32消息框,将结果传递给一个回调函数。
It just opens standard Win32 message box and passes the result to a callback function.
现在的问题是:是否有可能使用在Ruby中此功能,通过小提琴或类似的东西,并以某种方式传递一个Ruby的方法,以便它是从C ++中调用code
The question is: is it possible to use this function in Ruby, via Fiddle or something similar, and pass a Ruby method to it somehow so it is called from within the C++ code?
下面是code我用进口的DLL库红宝石:
Here is the code I use to import DLL library to Ruby:
require "fiddle"
myLibrary = Fiddle.dlopen("myLibrary.dll")
myFunction = Fiddle::Function.new(
myLibrary["myFunction"],
[Fiddle::TYPE_VOIDP],
Fiddle::TYPE_VOID
)
def myCallback(value)
puts "MessageBox result is #{value}"
end
这显然是行不通的:
And this obviously doesn't work:
myFunction.call(method(:myCallback))
这只是抛出一个TypeError - 不能转换法整数
It just throws a TypeError - can't convert Method to Integer.
有没有办法来传递回调到C函数?
Is there a way to pass the callback to the C function?
推荐答案
于是我找到了解决办法:
So I found the solution:
myClosure = Class.new(Fiddle::Closure) {
def call(value)
puts "MessageBox result is #{value}"
end
}.new(Fiddle::TYPE_VOID, [Fiddle::TYPE_INT])
然后,我可以简单地调用C函数:
Then I can simply call the C function:
myFunction.call(myClosure)
我真的不知道这是如何工作 - 但它工作得很好。
I don't really know how this works - but it works fine.
这篇关于红宝石 - 传递方法给DLL库作为回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!