簡體   English   中英

我可以在導出到c的c ++函數中使用`bool`類型或不透明指針嗎?

[英]Can I use `bool` type or opaque pointers to classes in a c++ function exported to c?

我正在編寫我正在編寫的庫的API。 庫本身將用c++編寫,但API將使用extern "C"導出,以實現最佳的跨語言兼容性(稍后我將使用C#C++C和其他一些語言來使用此API)。
顯然,API不能包含整個類或其他c++特定的功能(比如拋出異常),但我的問題是:

  1. 我可以在導出的API中使用bool類型嗎? 畢竟,這是一個POD。
  2. 我可以使用類的不透明指針嗎? 如果是這樣,我將如何在頭文件中聲明它們,以便可以從C代碼中使用頭文件?

Bool應該沒問題,ABI和語言設計人員對這些事情要謹慎(例如,C ++的complex<double>和C的complex double明確設計為兼容)。 可以使用前向聲明將類轉換為不透明指針。

#ifdef __cplusplus
class MyClass;
#else
#include <stdbool.h>
typedef struct MyClass MyClass;
extern "C" {
#endif

bool IsActivated(MyClass *p, int x);

#ifndef __cplusplus
}
#endif

請注意,如果設置了各種編譯器標志或屬性,我已經看到了ABI兼容性問題 - 例如,如果啟用了結構打包,則bool在使用GCC 4.2的C和C ++中的大小不同。

  1. 我可以在導出的API中使用bool類型嗎? 畢竟,這是一個POD。
  2. 我可以使用類的不透明指針嗎?

我終於繼續進行測試了。 以下是測試程序:

test_cpp.cpp:

#include "test.h"

class C {
    int a;
public:
    C() : a(42) {}
    int  getA() { return a; }
    void setA(int v) { a=v; }
};

int get7(bool b) { return b ? 7 : 3; }

C c;
C* getC() { return &c; }
int  getA(C* t) { return t->getA(); }
void setA(C* t, int v) { return t->setA(v); }

test_c.c:

#include <stdio.h>
#include "test.h"

int main()
{
    C* c = getC();
    printf("%d\n", getA(c));
    setA(c, 10);
    printf("%d\n", getA(c));
    printf("%d\n%d\n%d\n%d\n", get7(0), get7(1), get7(2), get7(-1));

    return 0;
}

test.h:

#ifdef __cplusplus
extern "C" {
#else
#define bool _Bool
#endif

struct C;
typedef struct C C;

int get7(bool b);

C* getC();
int  getA(C* t);
void setA(C* t, int v);

#ifdef __cplusplus
}
#endif

在windows上使用mingw64 gcc-4.9.0進行編譯

gcc -c test_c.c
g++ test_cpp.cpp test_c.o

它編譯並正確運行。 興趣點:

  • g++完全沒有問題, C被聲明為struct ,后來定義為class
  • c ++ boolc _Bool可互換使用

我嘗試使用MS編譯器(VS2012),除了一個我無法解釋的小細節外,它的工作方式相同:在頭文件中,我不得不改變

int get7(bool b);

int get7(bool);

讓它編譯。 如果有人能夠解釋這一點,我很樂意理解它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM