Hello,

TL;DR: Could building LuaMetaTeX with the `-fPIC` flag for the Lua library
have negative consequences? Is there a better way to be able to call
external C functions from ConTeXt?

I am working on a small project where it would be convenient to call
functions written in C (possibly pre-compiled in a shared library) from
ConTeXt. After looking at the Lua FFI, I found a way that seems to work
(with ConTeXt LMTX 2024-08-16) but requires a small tweak to the cmake file
used for building the Lua library. I would be grateful to have the opinion
of people more knowledgeable than I am about whether this change could have
negative consequences and whether there is a more straightforward way to
call external C code.

What I am trying to achieve is:
* Compile some C code in a shared library (for instance, it may contain a
numerical solver for some partial differential equation).
* Have this code run when compiling a document with ConTeXt. (For instance,
solving the differential equation with parameters defined in the .tex file
and retrieving the results to plot a figure with MetaPost.)

One easy way to do that is:
* Write wrappers for the functions that will need to be called from ConTeXt
using the Lua C API.
* Compile the code and wrappers in a shared library and linking to the
static lua library used by LuaMetaTeX (liblua.a on Linux).
* In the .tex file, import the new library using, e.g.,
```
\startluacode
    mylib = require("mylib")
    -- additional code using the C functions
\stopluacode
```
* Run ConTeXt with the `--permitloadlib` flag.

However, the second step requires (at least on Linux) liblua.a to be
compiled with the `-fPIC` flag. I could do that by adding
```
set_property(TARGET lua PROPERTY POSITION_INDEPENDENT_CODE ON)
```
at line 47 in lua.cmake. Is there any known negative effect of doing that
(apart from a possible small performance drop)?
(Just to be clear, this is not a feature request; I'm just wondering
whether doing it on my side is fine.)

On a related note, is there a standard way to call external C functions
(either in a shared library or in a .c file) from ConTeXt LMTX? The SwigLib
library described in
https://www.pragma-ade.nl/general/manuals/swiglib-mkiv.pdf looks very
promising (and maybe could be a way to achieve what I'm trying to do in a
much cleaner way), but I (maybe for lack of trying hard enough) have not
been able to make it work with ConTeXt LMTX so far.

Best regards,
Florent
___________________________________________________________________________________
If your question is of interest to others as well, please add an entry to the 
Wiki!

maillist : ntg-context@ntg.nl / 
https://mailman.ntg.nl/mailman3/lists/ntg-context.ntg.nl
webpage  : https://www.pragma-ade.nl / https://context.aanhet.net (mirror)
archive  : https://github.com/contextgarden/context
wiki     : https://wiki.contextgarden.net
___________________________________________________________________________________

Reply via email to