Using a freepascal library (.dylib) from mono
-
25-09-2019 - |
Question
While learning C# and Delphi Prism for use with monotouch is rewarding, I am looking for a way to re-use code written in ordinary Object Pascal. To simply re-write everything I have done in Delphi over 15 years is simply unacceptable.
So my question is twofold:
- If I for sake of argument have a library written in ordinary Object Pascal with no external dependencies and compiled with the ARM freepascal compiler for iPhone - could I use the resulting dylib from monotouch?
- If the above is correct, how do I declare and call these external functions from C#/Prism? How do i deal with passing record types etc. in mono?
I have noticed that other iPhone applications ship with their own dylib files (the SDL game library is a typical example). I find no reason why this should not work.
Solution
I have not worked with monotouch, but Mono/.NET have a feature called P/Invoke (platform invoke).
Basically you declare your functions/procedures as extern in the managed code and add a DLLImport
attribute.
In contrast to its name DLLImport
imports functions/procedures from .so
files on Linux and .dylib
files as well.
OTHER TIPS
I know nothing of monotouch, and less about Mac relating to Arm devices, but:
If your lib uses mostly the cdecl calling convention, and monotouch could maybe call cdecl (C) functions over some native operation mechanism (P/Invoke or JNI like stuff), that would be a base principle that could work.
The same for structures, declare with {$packrecords C}.
You might also need to call two functions (IIRC FPC_INITIIALIZE, and another one to finalize) to initialize/finalize the FPC RTL before calling functions.
Anything above the plain C level, such as Delphi Objects and such probably not usable, and must be wrapped. Maybe objective Pascal objects are reusable (at least if monotouch understands objective C ones), but like most other Apple specific stuff, that is not my forte.