提问者:小点点

尝试用cpp.so lib编译c代码,带有外部“c”{…}段


我需要用-lfoocpp 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 */
}

那我能这么做吗?


共1个答案

匿名用户

由于您想从C代码中使用您的lib,所以lib不能导出类。

你只能有功能。你可以把类隐藏在不透明的指针后面。

在库中,随心所欲地使用C++,只要所有接口函数都是plain-C,不使用类或指向类的指针即可。

例如,这个头有一个带有函数“add”的类“a”,并且还提供了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.

相关问题