开发者

Calling C++ code from C [duplicate]

This question already has answers here: 开发者_Go百科 Developing C wrapper API for Object-Oriented C++ code (6 answers) Closed 5 years ago.

Is there any way where I can call C++ code from C code?

class a
{
  someFunction();
};

How to call someFunction() from a C code? In other words, I am asking how to avoid name mangling here.


  1. First, write a C API wrapper to your object-based library. For example if you have a class Foo with a method bar(), in C++ you'd call it as Foo.bar(). In making a C interface you'd have to have a (global) function bar that takes a pointer to Foo (ideally in the form of a void pointer for opacity).
  2. Wrap the DECLARATIONS for the C API you've exported in extern "C".

(I don't remember all the damned cast operators for C++ off-hand and am too lazy to look it up, so replace (Foo*) with a more specific cast if you like in the following code.)

// My header file for the C API.
extern "C"
{
  void bar(void* fooInstance);
}

// My source file for the C API.
void bar(void* fooInstance)
{
  Foo* inst = (Foo*) fooInstance;
  inst->bar();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜