Win8 Metro C# 调用 C++代码

本文介绍如何在 Win8Store App 中使用 C++ 静态库,通过 C++/CX 封装使得 C# 代码能够调用 C++ 实现的功能,例如数学运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@井九

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值