admin管理员组

文章数量:1794759

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

代码语言:javascript代码运行次数:0运行复制
#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)

代码语言:javascript代码运行次数:0运行复制
#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' 

代码语言:javascript代码运行次数:0运行复制
#pragma once

namespace wrc
{
    public ref class Class1 sealed
    {
    public:
        Class1();
 		double Class1::Add(double a, double b);
   };
}

'Class1.cpp' 

代码语言:javascript代码运行次数:0运行复制
#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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2024-10-11,如有侵权请联系 cloudcommunity@tencent 删除doubleincludepropertiesc++c#

本文标签: Win8 Metro C 调用 C代码