【问题标题】:How to assign function to Rebol struct member如何将函数分配给 Rebol 结构成员
【发布时间】:2018-06-25 15:06:52
【问题描述】:

我先定义一个函数ADD:

add: func [ a [integer!] b [integer!] ] [a + b]

然后是一个结构体:

s: make struct! [
    sadd [ function! ]
] add

但是Rebol struct 不支持FUNCTION!数据类型。如何将函数分配给 Rebol 结构?

【问题讨论】:

  • 你为什么要这么做?
  • 如果可能请告诉我。我想使用来自 c 的例程,它带有一个参数(struct)。最终该结构拥有一个回调函数。
  • 请注意,Rebol 类型与 C 类型之间存在“一对多”映射。例如,C 回调可能需要 intshort...。如果您只说 INTEGER! ,则不可能自动知道哪个是预期的。这就是为什么常规!存在,并且它不能(安全地)仅从 FUNC 定义中做出自动假设……您必须描述低级类型是什么。另外需要注意的是,按值传递的 C 结构在 C 中没有正式定义。另见 this Q&A

标签: ffi rebol rebol2


【解决方案1】:

回调是 Rebol2 的 alpha 功能。有关文档,请参阅 Carl 的 article

基本上,如果您有一个 dll,例如 test-lib.dll,其中测试函数接受两个整数并再次原封不动地返回它们

extern "C"
MYDLL_API int test(int a, int b, int (*pFunc)(int, int))
{
   int result = pFunc(a, b);
   return result;
}

你会像这样从 Rebol 编写调用函数

test: make routine! [
    a [int]
    b [int]
    c [callback [int int return: [int]]]
    return: [int]
] test-lib "test"

所以,这个测试函数将两个整数作为参数,第三个参数是一个 Rebol 函数,用作回调。例程中的回调!是一个关键字。块规范自动变成structure!

回调函数是这样写的,它接受库调用返回的两个整数,将它们相加,然后返回。

add-it: func [a b][return a + b]

然后就这样使用

>> test 1 2 :add-it
== 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多