【问题标题】:Trying to compile c code with cpp .so lib, with extern "C" { ... } segment尝试使用 c++ .so 库编译 c 代码,带有 extern "C" { ... } 段
【发布时间】:2020-11-12 14:15:59
【问题描述】:

我需要用-lfoo cpp lib编译c代码。

foo.cpp 看起来像:

#include "foo.hpp"

extern "C" {
/* some come for my class, that describes in  foo.hpp*/
}

foo.hpp:

class Bar{
public:
/* public fields  */
/* public methods */
}

那我可以这样做吗?

【问题讨论】:

  • 如果这是您所要求的,您不能使用 C 代码中的 C++ 类。常见的解决方法是提供一组为您调用方法的 C++ 函数。
  • 您的 C 代码需要使用带有 C 接口的有效 C 标头(并且您需要定义这样的接口)。 extern "C" 仅影响命名,它不会自动使您的 C++ 代码可在 C 中使用。
  • @Botje 我猜是一组 C 函数。
  • C++ 可以使用 C 例程。 C 例程不能使用 C++ 对象(不能直接使用;可以制作与 C 兼容的接口,但这不是自动的,您必须自己制作)。
  • @evg C++ 函数带有 extern "C" 标签,使它们可以从 C 中调用而不会被修改。

标签: c++ c gcc


【解决方案1】:

由于您想从 C 代码中使用您的库,因此该库无法导出类。

你只能拥有功能。您可以将类隐藏在传递出去的不透明指针后面。

在库中,随意使用 C++,只要所有接口函数都是纯 C 且不使用类或指向类的指针。

例如,这个头文件有一个类 'A' 和一个函数 'add' ,并且还提供了 3 个函数来使用来自 C 调用者的功能。

#pragma once

#ifdef __cplusplus

// the class-definition is hidden when included from C.
class A
{
  public:
    A(int val);

    int add(int b) const;
  private:
    int m_val;
};

extern "C"
{
#endif

// exported functions. Exported in C compatible way.

// create an 'A', pass out as void*
void *create(int val);

// destroy the 'A' object. Call destroy inside.
void destroy(void *hdl);

// use the exported function. hdl is the return value from 'create()'.
int add_A(void *hdl,int b);

#ifdef __cplusplus
}
#endif

在里面,函数将类包裹起来并隐藏起来。

void *create(int val)
{
    return new A(val);
}

void destroy(void *hdl)
{
    delete ((A*)hdl);
}

int add_A(void *hdl,int b)
{
    return ((A*)hdl)->add(b);
}

A::A(int val)
{
 ////........... implementation of A class follows here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    • 2020-03-07
    • 2020-09-20
    相关资源
    最近更新 更多