Passing pointers from C to C ++ and vice versa

Are there any tips you can give me about passing pointers to structures, paired, functions, ... from a C program to a C ++ library and vice versa?

+5
source share
3 answers

Assuming you code them in two different libraries, static or dynamic (DLLs on shared Windows libraries on Linux and other * nix variants). The biggest problems that I have are the following:

  • They are compiled with the same compiler. Although this is not necessary if all C ++ exports are exported using a C-style naming convention, it is necessary that C ++ - C ++ call class instances between two C ++ modules. This is necessary because of how different compilers change C ++ exports in different ways.

  • Do not use the C ++ class as a C structure. They do not match the covers, even if the layout of the fields is the same. C ++ classes have a "v-table" if they have virtual members; this v-table allows you to correctly name the inherited or base class methods.

  • This applies to C in C or C ++ in C ++, as well as in C in C ++. Make sure they use the same byte alignment for the output library. You can only determine this by reading the documentation of your compiler or development environment.

  • malloc/free /. , "" . - .

  • : , / ++ "extern" C "'', . ( , , C ++, , - )

  • : C, ++, .

  • ++ C C, C- , ++. C ++.


    Pseudocode-ish Example:
    // C++ class
    class foo {
       public:
           void DoIt();
    };

    // export helper declarations
    extern "C" void call_doit(foo* pFoo);
    extern "C" foo* allocate_foo();
    extern "C" deallocate_foo(foo* pFoo);


    // implementation
    void call_doit(foo* pFoo)
    {
        pFoo->DoIt();
    }

    foo* allocate_foo()
    {
        return new foo();
    }

    deallocate_foo(foo* pFoo)
    {
       delete pFoo;
    }

    // c consumer
    void main()
    {
        foo* pFoo= allocate_foo();
        call_doit(pFoo);
        dealocate_foo(pFoo);
    }


+10

C ++ - , C/++.

, - , , , ( ).

, ? .

0
  • Do not forget the extern keyword "C" . avoid problems with C ++ - name manipulation.
  • Do not use the pass by reference argument parameter, but a pointer
0
source

All Articles