LoginSignup
10
18

More than 3 years have passed since last update.

【C++】C++で作成したDLLをC++で呼ぶ(静的)

Last updated at Posted at 2019-04-02

もくじ
https://qiita.com/tera1707/items/4fda73d86eded283ec4f

やりたいこと

C++で作ったDLLを、C++から、静的に呼び出したい。

静的にDLLを呼ぶ

やり方は、下記の2つある。
このうち、静的に呼び出すのを今回やる。
(動的に呼ぶ方はこちらを参照。)

呼出方法 やり方概要 DLL読込タイミング 必要ファイル
静的 DllImportして、必要な関数をextern宣言し、使用する。※1 プログラム開始時 dllファイル(実行時)/libファイル(ビルド時)
動的 LoadModuleでDllを読込み、LoadLibraryで関数を読込む。※2 任意 dllファイル(lib不要)

※1
関数のプロトタイプ宣言とLIBファイルの指定(コンパイラオプションでの指定または#pragma)のみで通常の関数の様に使える。
※2
LIBファイル・ヘッダーファイルのないDLLに使用できる。

DLL側(C++)

以前の記事で書いたものと同じのを使う。

呼びだす側(C++)

.libファイルの参照設定

まず、Dllと対になる.libファイルを参照するように設定追加する。

  • pjのプロパティ > リンカー > 入力 の、追加の依存ファイルに、必要な.lib(ここではDllTest.lib)を追加image.png

  • pjのプロパティ > リンカー > 全般 の、追加のライブラリディレクトリに、その.libのあるフォルダを追加image.png

※libの設定は、コード中に#pragmaでも実施できる様子。(今回は試さず)
 下記を参照。

 http://yamatyuu.net/computer/program/sdk/base/static_dll/index.html

DllImportの実施

DllImportを行う。
今回は、Dll側の.hをインクルードすればDllImportできるようにしているので、そのようにする。

DLLを使う側では「VC_DLL_EXPORTS」は「extern "C" __declspec(dllimport)
」となる。(VC_DLL_EXPORTSが#defineされないため)

DllTest.h
#ifdef VC_DLL_EXPORTS
#undef VC_DLL_EXPORTS
#define VC_DLL_EXPORTS extern "C" __declspec(dllexport)
#else
#define VC_DLL_EXPORTS extern "C" __declspec(dllimport)
#endif

// エクスポート関数のプロトタイプ宣言
VC_DLL_EXPORTS void __cdecl Test_MyApi();
VC_DLL_EXPORTS void __cdecl Test_MyApi2(const wchar_t* lpText, const wchar_t* lpCaption);
VC_DLL_EXPORTS void __cdecl Test_MyApi3(int count);

※.hファイルは、Dll側の.hファイルを使う。(逆にいうと、.hファイルがないと、このやり方はできない?→「動的」に使うやり方でやる?)

Dllの関数を呼ぶ

.cppファイルは、普通の関数のように呼ぶだけ。

ConsoleApplication1.cpp
#include "pch.h"
#include <iostream>
#include <windows.h>
#include <string.h>

#include "DllTest.h" 

int main()
{
    Test_MyApi();
    Test_MyApi2(L"あああ", L"いいい");
    Test_MyApi3(2);
}

参考

呼び出し規約の種類(cdeclとか、stdcallとか)
https://konuma.org/blog/2006/01/02/post_1fd3/

extern "C" とは?
https://konuma.org/blog/2006/01/04/post_144e/

DLLを静的リンクで呼び出す
http://yamatyuu.net/computer/program/sdk/base/static_dll/index.html

コード

10
18
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
10
18