5

I have some cpp files, and I want to combine them with LuaJit using FFI.

But the problem is that, I have to add extern "c" symbols for almost every function to make it possible for FFI to access them.

Is there a simpler way to make this done?

Zehui Lin
  • 186
  • 9
  • 7
    you can group all the functions in a single extern C block. Isn't that enough? – Jean-François Fabre Aug 26 '16 at 08:42
  • 1
    The cpp files are not created by myself, I know nothing except their functions. I just want to use them through Lua. – Zehui Lin Aug 26 '16 at 09:01
  • First of all, did you check that all your functions are `extern "C"`-ready? I.e. do they use only C types (no references, no classes etc.)? `extern "C"` only turns off name mangling. – Sergio Aug 26 '16 at 09:02
  • @Serhio So not all functions can be mark `extern "C"`? Then it would be really difficult if I want to use opensource cpp files for my Lua project. – Zehui Lin Aug 26 '16 at 09:08
  • What do you expect? Miracles? The whole point of `extern "C"` is to provide an interface to C code, by disallowing features that are incompatible with C. If Lua requires a C interface, it is not possible to use features specific to C++ across that interface. If you want to use opensource C++ files in your project, you need to provide an `extern "C"` set of functions which are compiled using a C++ compiler, and use capabilities of C++ in their implementation. – Peter Aug 26 '16 at 09:26
  • 2
    @ZehuiLin You can mark with `extern "C"` whatever function you want, but it doesn't mean that all marked functions will be C-compatible. – Sergio Aug 26 '16 at 09:35
  • 1
    Thank you for your advice. I read the code, and found that I can add one `extern "C"` block for it. It seems working now. – Zehui Lin Aug 29 '16 at 14:12

3 Answers3

0

Several functions can be placed inside a single extern "C" block. This allows you to type extern "C" only once for each header file.

extern "C" {
    void function1();
    void function2();
}
VLL
  • 9,634
  • 1
  • 29
  • 54
0

Though it is non-portable, you could implement a function signature and generates the Mangled name using the name mangling protocol to find the symbol name for FFI.

Gcc and Clang on Linux use the Itanium C++ ABI Name Mangling Rules, which can be found here.

On Windows, MSVC uses a non-documented name mangling scheme.

Paul Belanger
  • 2,354
  • 14
  • 23
0

Yes. Define a simple, minimal, wrapper API and export it:

// NOTE: Exported functions do heavy parley and medical-research leveraging C++ under the hood (and only and the hood).
extern "C" {
  void achieve_world_peace(void);

  void treat_cancer(void);
}
Abdullah
  • 711
  • 7
  • 5