Elegantly call C++ from C

前端 未结 4 1875
不知归路
不知归路 2020-11-28 23:04

We develop some project in plain C (C99). But, we have one library as source codes (math library) in C++. We need this library so I would like to a

4条回答
  •  迷失自我
    2020-11-29 00:05

    There is a way to create a "hack" that allows you to call member functions of some objects directly.

    The first thing you have to do is to create an extern "C" factory function, which returns a pointer (as void*) to the object.

    The second thing you need is the mangled name of the member function.

    Then you can call the function using the mangled name, and passing the pointer returned from the factory function as the first argument.

    Caveats:

    • Will of course not work calling member function that wants other objects, or references, or other C++ stuff, or functions returning objects or types not compatible with C types
    • Will not work on virtual member functions, and probably not on objects with virtual functions in them even if it's not a virtual function being called
    • The mangled name have to be a valid C symbol
    • Any many many more...

    This is not something I recommend, quite the opposite in fact. I strongly advise against doing something like outlined in this answer. It's unsupported and probably undefined behavior and may break in weird and unpredictable ways.

提交回复
热议问题