Recent

Author Topic: How to invoke a function written by rust?  (Read 471 times)

AllenDang

  • Newbie
  • Posts: 2
How to invoke a function written by rust?
« on: July 16, 2024, 09:28:45 am »
Hi, guys

I'm thinking of write functions in rust, compile it to library (static/shared), and invoke them from FPC.
I searched a lot both in google/lazarus wiki/lazarus forum, but cannot find valid information about FFI related stuff.

Here are my questions:

1. is it possible to write functions in rust, compile it to static linked lib and link it in lazaru in order to build a single executable? Ideally I should build the static lib for macOS/linux/windows so I can distribute single cross-platform executable to user.

2. is it possible to build the rust functions into shared lib and invoke functions in lazarus?

If there is any document I could study about FFI, it will be much appreciated.

Any hint will be much helpful, thanks!

Khrys

  • Full Member
  • ***
  • Posts: 105
Re: How to invoke a function written by rust?
« Reply #1 on: July 16, 2024, 10:04:12 am »
I'd suggest reading part 7.1 (Using external code and variables) of the FPC programmer's manual, it's part of the official documentation and explains everything quite nicely.

In theory it shouldn't matter at all which languages are used in libraries, as long as the output is a compatible object file and matching calling conventions are used. One problem that can arise in reality however is that the library's runtime (language-dependent) might not get initialized automatically. This would indeed be a problem in a hypothetical reverse scenario of yours (using FPC libraries in a Rust project). There's recently been a thread about that exact issue:

Possibly as this is a static library the runtime isn't getting initialised automatically. Does anyone know how to make that work?

That is correct. FPC code is not designed to be usable as a static library. If you want to go this route you need to make sure that you call FPC_INITIALIZEUNITS (it's exported with that uppercase symbol name from the System unit (and thus its object file)).

Anyway, in your case using  #![crate_type = "staticlib"]  or  #![crate_type = "cdylib"]  should do the trick...

AllenDang

  • Newbie
  • Posts: 2
Re: How to invoke a function written by rust?
« Reply #2 on: July 16, 2024, 10:13:23 am »
Thanks a lot!

 

TinyPortal © 2005-2018