在C中调用C ++ code [英] calling c++ code from c

查看:145
本文介绍了在C中调用C ++ code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法,我可以调用C ++ code从C code

 
{
  someFunction();
};

如何调用 someFunction()从C code。

在其他的方式,我问如何避免名称重整这里

问候
Vinayaka Karjigi


解决方案

  1. 首先,写一个C API包装到基于对象的库。例如,如果你有一个类Foo有法巴(),在C ++中你会称呼其为Foo.bar()。在作出一个C接口,你得有一个(全局)的功能栏,需要一个指针来富(最好在一个不透明void指针的形式)。

  2. 包裹的声明为C API你的externC已经出口。

(我不记得所有的该死的投运营商C ++的副手和我懒得看它,所以用一个更具体的投替换(富*)如果您在以下code喜欢。 )

对于C API

  //我的头文件。
为externC
{
  空巴(无效* fooInstance);
}//为C API我的源文件。
空巴(无效* fooInstance)
{
  美孚*研究所=(美孚*)fooInstance;
  inst->巴();
}

is there any way where I can call c++ code from a c code

class a
{
  someFunction();
};

how to call someFunction() from a c code.

in other way I am asking how to avoid name mangling here

regards Vinayaka Karjigi

解决方案

  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();
}

这篇关于在C中调用C ++ code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆