1

I first define a function ADD:

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

Then a struct:

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

But Rebol struct does not support the FUNCTION! datatype. How can I assign a function to a Rebol struct?

  • Why do you want to do that? – Graham Chiu Jun 25 '18 at 22:18
  • if it is possible pls let me know. I want to use a routine from c which take an argument (struct ). eventually the struct holds a callback funation. – Raton Kumar Jun 26 '18 at 02:21
  • Note there is a "one to many" mapping of Rebol types to C types. A C callback might expect an `int` or a `short`...for instance. It's not possible to automatically know which is expected if you just say INTEGER!. This is why ROUTINE! exists, and it can't (safely) make an automatic assumption just from a FUNC definition...you have to describe what the low-level types are. As another thing to be aware of, C structures passed by value have no formal definition in C. See also [this Q&A](https://stackoverflow.com/q/4931195/211160). – HostileFork says dont trust SE Jun 26 '18 at 07:55

1 Answers1

2

Callbacks are an alpha feature of Rebol2. See Carl's article for documentation.

Essentially, if you have a dll such as test-lib.dll where the test function takes two integers and returns them again unchanged

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

you would write the calling function from Rebol like this

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

So, this test function takes two integers as parameters and a third parameter which is a Rebol function to be used as a callback. The callback in the routine! is a keyword. The block specification is automatically turned into a structure!

The callback function is written like this which takes the two integers returned by the library call, adds them, and returns them.

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

And it's then used like this

>> test 1 2 :add-it
== 3
Graham Chiu
  • 4,856
  • 1
  • 23
  • 41