Win8 Metro C# 调用 C++代码

在写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;
}



Win8 Metro C# 调用 C++代码,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。