VS中新建一個動態庫項目
文件生成一個工程名對應的.cpp文件,該文件定義 DLL應用程序的導出函數。
工程內新建一個類OutputInt,我用類向導生成,工程中會添加OutputInt.cpp和OutputInt.h兩個文件,
在.h文件中聲明函數
#pragma once class OutputInt { public: OutputInt(); ~OutputInt(); static _declspec(dllexport) int TestFunction(); };
在.cpp文件中實現 構造函數、析構函數和 自定義函數
#include "stdafx.h" #include "OutputInt.h" OutputInt::OutputInt() { } OutputInt::~OutputInt() { } int OutputInt::TestFunction() { return 111; }
類和頭文件都實現了。
然后在Win32Project1.cpp中定義對外暴露的函數
#include "stdafx.h" #include "OutputInt.h" extern "C" __declspec(dllexport) int TestFunction() { OutputInt outPut; return outPut.TestFunction(); }
編譯,生成對應工程項目名的DLL文件,動態鏈接庫生成完成。
在C# WPF應用程序中調用以上生成的DLL
把生成的DLL文件拷貝到 WPF工程的DEBUG文件夾下,調用方式:
[DllImport("Win32Project1.dll", ExactSpelling = false)] public static extern int TestFunction();
調用完成。