Search code examples
c++pythonccalling-convention

different programming language and calling convention


According to the wiki:

Different programming languages use different calling conventions, and so can different platforms (CPU architecture + operating system). This can sometimes cause problems when combining modules written in multiple languages

So am I supposed to be careful when I call C/C++ functions (exported from .so/.dll) in Python? If yes, what should I be careful of?


Solution

  • The calling convention is not an issue when calling C from python because the python interpreter itself is written in C, and thus uses the same calling convention as the C code.

    It becomes an issue when combining code written in different compiled languages, for example C and Ada.

    Usually C is the system programming language, and thus the standard. This means that a compiler for any language will generally have special support to inter-operate with C. See here for an example of interoperability between C and Ada. If there is no special support wrappers must be written at the assembly level.

    If you need to call C++/Ada from python you'll have to follow a two steps process. The first step is to write a C wrapper around the C++/Ada functions. The second step is to call the C wrapper from python.

    Take for example the following C++ class.

    class Foo
    {
    public:
      Foo ();
      int bar ();
      ...
    };
    

    If you want to make it available to python, you first need to wrap it in C:

    extern "C" {
    typedef void *FooPtr;
    FooPtr foo_new () { return (FooPtr)new Foo(); }
    int foo_bar (FooPtr foo) { return ((Foo*)foo)->bar(); }
    ...
    }
    

    Then you can call that from python. (Note, in real life there are tools to automate this, like Boost.Python).

    Note that there are two aspects of writing a wrapper: converting between calling conventions and converting between type representations. The later part is usually the most difficult because as soon as you go beyond basic types languages tend to have very different representations of equivalent types.