Can I make function `extern "c"`?
Asked Answered
C

3

6

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?

Companionway answered 26/8, 2016 at 8:40 Comment(7)
you can group all the functions in a single extern C block. Isn't that enough?Maiduguri
The cpp files are not created by myself, I know nothing except their functions. I just want to use them through Lua.Companionway
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.Galiot
@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.Companionway
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.Lissner
@ZehuiLin You can mark with extern "C" whatever function you want, but it doesn't mean that all marked functions will be C-compatible.Galiot
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.Companionway
J
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();
}
Jannajannel answered 26/8, 2016 at 8:41 Comment(0)
I
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.

Ipa answered 1/5, 2018 at 17:21 Comment(0)
D
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);
}
Daytoday answered 28/5, 2022 at 5:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.