iT邦幫忙

4

[筆記]C#呼叫C++動態連結庫(DLL) + Debug

Kevin 2018-09-15 18:52:4528625 瀏覽

前言

接下來介紹影像處理提取特徵,所以首先要先做好環境設定,這次介紹如何呼叫dll來Debug。

創建C++ DLL

1.選擇DLL和空專案。
https://ithelp.ithome.com.tw/upload/images/20180915/20110564OVJY65wBzH.png

2.設定支援CLR讓.NET可呼叫。
https://ithelp.ithome.com.tw/upload/images/20180915/20110564GRXXIrYOCx.png

3.創建一個class和一個寫入檔案的函數。
Library.h

#pragma once
#ifndef LIBRARY_H
#define LIBRARY_H

#include <fstream>
#include <string>

class Library
{
public:
	Library();

	~Library();

	void Write(const char* str);
private:
	const char* LOG_FILE;
	std::fstream _fwLog;
};

#endif // !LIBRARY_H

4.實作函數。
Library.cpp

#include "Library.h"

Library::Library()
{
	LOG_FILE = "D:\\Log.txt";
	_fwLog.open(LOG_FILE, std::ios::app);
}

Library::~Library()
{
	_fwLog.close();
}

void Library::Write(const char* str)
{
	_fwLog << str;
}

5.匯出DLL函數,呼叫時為mndtWrite。
MNDTLibrary.cpp

#ifdef MNDTLIBRARY_EXPORTS
#define MNDTLIBRARY_API __declspec(dllexport)
#include "Library.h"

extern "C" MNDTLIBRARY_API void mndtWrite(const char* msg)
{
	Library lib;
	lib.Write(msg);
}

#else
#define MNDTLIBRARY_API __declspec(dllimport)
#endif

6.我這邊使用x64編譯。

創建C#

1.設定unsafe(後面會使用到指標來傳資料),和x64編譯。
https://ithelp.ithome.com.tw/upload/images/20180915/20110564CfPm5uOGyT.png

2.創建class呼叫C++匯入函數使用,這邊我指定路徑讀取C++編譯的DLL。
MNDTLibrary.cs

class MNDTLibrary
{
    private const string DLL_PATH = @"D:\Visual Studio 2013 Project\Projects\MNDTLibrary\x64\Debug\MNDTLibrary.dll";

    [DllImport(DLL_PATH)]
    private static extern void mndtWrite(string msg);

    public void Write(string msg)
    {
        mndtWrite(msg);
    }
}

3.呼叫Write寫入D:/Log.txt。
Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        MNDTLibrary mndt = new MNDTLibrary();
        mndt.Write("Hello World");
    }
}

4.我這邊使用x64編譯。

Debug設定

Debug設定只需要在C++ Dll檔那邊設定C#編譯出來的exe路徑,按下Debug即可。

1.設定位置。
https://ithelp.ithome.com.tw/upload/images/20180915/20110564Jj1p7DtUUS.png

結語

接下來要介紹一些影像的色彩轉換,這篇文獻因為有點久遠忘記參考哪篇所以這次沒打文獻請見諒。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
ajeams
iT邦新手 4 級 ‧ 2018-09-23 02:08:55

感謝分享!

我要留言

立即登入留言