现在的位置: 首页 > 综合 > 正文

Win8 Metro C# 调用 C++代码

2014年04月29日 ⁄ 综合 ⁄ 共 1031字 ⁄ 字号 评论关闭

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


抱歉!评论已关闭.