在寫Win8 Store App 的時候,可能遇到需要調用C++的代碼。
比如有個壓縮算法,Lz77,有C++的實現,改成C#實現需要很多時間,所以通過C++/CX包裝一下,C#就能直接調用C++的實現了。
首先創建C++靜態庫。必須使用extern “C”,同時使用#pragma once還避免重複include,用#ifndef __SOMEFILE_H__方式可能會報鏈接錯誤。
同時設置工程屬性
staticLibrary Project Properties:
staticLibrary -> Properties -> C/C++ -> General -> Consume Windows Runtime Extension ->Yes (/ZW)
staticLibrary.h
#pragma once #ifdef __cpluscplus extern "C" { #endif // Returns a + b double sLibAdd(double a, double b); #ifdef __cpluscplus } #endif
staticLibrary.cpp,如果這裏是.c後綴的話,需要設置staticLibrary.c -> Properties -> C/C++ -> Advanced -> Compile As -> Compile as C++ Code (/TP)
#include "pch.h" #include "staticLibrary.h" double sLibAdd(double a, double b) { return a + b; }然後創建Windows RunTime Component:
wrc裏面,Array<uint8>^ 類型,在C#裏面能直接用byte[]對應。
'Class1.h'
#pragma once namespace wrc { public ref class Class1 sealed { public: Class1(); double Class1::Add(double a, double b); }; }
'Class1.cpp'
#include "pch.h" #include "Class1.h" #include "staticLibrary.h" using namespace wrc; using namespace Platform; Class1::Class1() { } double Class1::Add(double a, double b) { double retVal = 0; retVal = sLibAdd(a, b); return retVal; }