0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++のsingletonクラスをC言語から呼び出す

Posted at

手順

概要

sampleclass をシングルトンとして実装し、C 言語から呼び出せるようにラッパーを提供する。

手順

1. sampleclass.hpp の作成

  • シングルトンのクラス sampleclass を定義します。
  • プライベートコンストラクタを使用し、コピーコンストラクタと代入演算子を削除してシングルトンを実現します。

2. sampleclass.cpp の作成

  • sampleclass の実装を記述します。
  • インスタンスは静的メンバ変数として確保します。
  • getInstance() メソッドでインスタンスを返します。

3. c_interface_wrapper.cppc_interface_wrapper.hの作成

  • extern "C" ブロック内に C 言語から呼び出せる関数を定義します。
  • シングルトンインスタンスを getInstance() で取得してメソッドを呼び出すようにします。

4. main.c の作成

  • C 言語から sampleclass のメソッドを呼び出すコードを記述します。
  • #ifdef __cplusplus ディレクティブで C++ と C のコンパイルを可能にします。

ファイル構成

  • sampleclass.hpp: クラス定義
  • sampleclass.cpp: クラス実装
  • c_interface_wrapper.cpp: C 言語インタフェースラッパー
  • c_interface_wrapper.h: C 言語インタフェースラッパー(ヘッダ)
  • main.c: C 言語からの呼び出し例

sampleclass.hpp

サンプルとなるシングルトンなクラス(ヘッダ)

#ifndef SAMPLECLASS_H
#define SAMPLECLASS_H

class sampleclass {
public:
    static sampleclass* getInstance();
    void procA(void);
    void porcX(int val);

private:
    sampleclass() = default; // コンストラクタをプライベートにしてシングルトンを実現
    sampleclass(const sampleclass&) = delete; // コピーコンストラクタの削除
    sampleclass& operator=(const sampleclass&) = delete; // 代入演算子の削除
    static sampleclass instance;
};

#endif

sampleclass.cpp

サンプルとなるシングルトンなクラス(本体)

#include "sampleclass.hpp"

sampleclass sampleclass::instance;

sampleclass* sampleclass::getInstance() {
    return &instance;
}
void sampleclass::procA(void) {
}
void sampleclass::porcX(int val) {
}

c_interface_wrapper.cpp

クラスをC言語から呼び出すためにエクスポートする

#include "sampleclass.hpp"

extern "C" {

    // C インタフェース関数
    void sampleclass_procA() {
        sampleclass::getInstance()->procA();
    }

    void sampleclass_procX(int val) {
        sampleclass::getInstance()->porcX(val);
    }

}

c_interface_wrapper.h

クラスをC言語から呼び出すためにエクスポートするためのヘッダ

#ifndef WRAPPER_DEF_H
#define WRAPPER_DEF_H

#ifdef __cplusplus
extern "C" {
#endif

	void sampleclass_procA();
	void sampleclass_procX(int val);

#ifdef __cplusplus
}
#endif

#endif

main.c

#include "wrapper_def.h"

int main() {
    sampleclass_procA();
    sampleclass_procX(42);
    return 0;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?