トップページへ

CからC++のクラスを利用する方法

小粋空間 » Programming Language » C/C++ » CからC++のクラスを利用する方法

CからC++のクラスを利用する方法を紹介します。

1.問題点

下記のC++プログラムを作りました。

foo.h

class Foo {
public:
    Foo();
    int abc(void);
};

foo.cc

#include "foo.h"
#include <iostream>
 
Foo::Foo() {}
 
int Foo::abc(void) {
    std::cout << "OK\n";
}

このC++プログラムをCのプログラムからアクセスしたいのですが、方法が分かりません。

ということで、CからC++のクラスを利用する方法を紹介します。

2.CからC++のクラスを利用する

やり方は色々あると思いますが、ここではC++プログラムにCからアクセスするためのラッパーを追加する方法を紹介します。

foo.h

#ifdef __cplusplus
extern "C" {
#endif
 
class Foo {
public:
    Foo();
    int abc(void);
};
 
void construct();
void execute();
void destruct();
 
#ifdef __cplusplus
}
#endif

ヘッダfoo.hには、ラッパー関数construct()、execute()、destruct()を宣言し、全体を「extern "C"」で括ります。「extern "C"」については「extern "C"の意味」をご覧ください。

foo.cc

#include "foo.h"
#include <iostream>
 
Foo::Foo() {}
 
int Foo::abc(void) {
    std::cout << "OK\n";
}
 
Foo *foo;
void construct() {
    foo = new Foo() ;
}
 
void execute() {
    foo->abc();
}
 
void destruct() {
    delete(foo);
}

foo.ccでは各ラッパー関数からクラスにアクセスするよう実装します。

Cのプログラム(test.c)は次のように書きます。

test.c

extern construct();
extern execute();
extern destruct();
 
int main() {
    construct();
    execute();
    destruct();
}

C++のラッパー関数はextern宣言します。

ビルドは、C++のコンパイルはg++、Cのコンパイルはgcc、リンケージはg++で行います。

% gcc -c test.c
% g++ -c foo.cc
% g++ -o a.out foo.o test.o

その他、上記のサンプルではラッパー内でnewを実施しないと実行時にセグメンテーションフォルトになったため、もしかしたらコンストラクタの実装が必要かもしれません。

« 前の記事へ

次の記事へ »

トップページへ