Macaulay2 » Documentation
Packages » ForeignFunctions » foreignFunction
next | previous | forward | backward | up | index | toc

foreignFunction -- construct a foreign function

Description

Load a function contained in a shared library using the C function dlsym and declare its signature. The library may be omitted if it is already loaded, e.g., for functions in the C standard library or libraries that Macaulay2 is already linked against.

i1 : mycos = foreignFunction("cos", double, double)

o1 = cos

o1 : ForeignFunction
i2 : mycos pi

o2 = -1

o2 : ForeignObject of type double

If a function takes multiple arguments, then provide these argument types using a list.

i3 : myatan2 = foreignFunction("atan2", double, {double, double})

o3 = atan2

o3 : ForeignFunction
i4 : myatan2(1, sqrt 3)

o4 = .5235987755982989

o4 : ForeignObject of type double

For variadic functions, set the Variadic option to true.

i5 : sprintf = foreignFunction("sprintf", void, {charstar, charstar},
         Variadic => true)

o5 = sprintf

o5 : ForeignFunction
i6 : buf = charstar "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

o6 = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

o6 : ForeignObject of type char*
i7 : sprintf(buf, "%s %d", "foo", 3)
i8 : buf

o8 = foo 3

o8 : ForeignObject of type char*

The variadic arguments are processed using foreignObject, which may lead to unexpected behavior. It may be useful to cast them to foreign objects to avoid ambiguity.

i9 : sprintf(buf, "%s %.1f", "foo", 3)
i10 : buf

o10 = foo 0.0

o10 : ForeignObject of type char*
i11 : sprintf(buf, "%s %.1f", "foo", double 3)
i12 : buf

o12 = foo 3.0

o12 : ForeignObject of type char*

Note that variadic functions cannot be passed arguments that have a size of fewer than 4 bytes.

i13 : stopIfError = false

o13 = false
i14 : sprintf(buf, "%c", char' 77)
stdio:15:7:(3): error: libffi: bad argtype

If the foreign function allocates any memory, then register a finalizer for its outputs to deallocate the memory during garbage collection using registerFinalizer(ForeignObject,Function).

i15 : malloc = foreignFunction("malloc", voidstar, ulong)

o15 = malloc

o15 : ForeignFunction
i16 : free = foreignFunction("free", void, voidstar)

o16 = free

o16 : ForeignFunction
i17 : x = malloc 8

o17 = 0x7f446406f230

o17 : ForeignObject of type void*
i18 : registerFinalizer(x, free)

Ways to use foreignFunction:

  • foreignFunction(Pointer,String,ForeignType,VisibleList)
  • foreignFunction(SharedLibrary,String,ForeignType,ForeignType)
  • foreignFunction(SharedLibrary,String,ForeignType,VisibleList)
  • foreignFunction(String,ForeignType,ForeignType)
  • foreignFunction(String,ForeignType,VisibleList)

For the programmer

The object foreignFunction is a method function with options.


The source of this document is in ForeignFunctions.m2:1931:0.