且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Windows 8 C#调用C++编写的Windows运行时组件

更新时间:2022-08-29 09:01:31

 

Windows运行时组件是Windows 8里面通用的公共库,它可以使用C++,C#或者VB来编写,不过你的Windows 8 metro是用什么语言编写都可以调用无缝地调用Windows运行时组件。

下面通过一个C#编写的Windows 8项目来调用一个用C++编写的Windows运行时组件。

创建一个Windows运行时组件:

Windows 8 C#调用C++编写的Windows运行时组件

编写如下的代码:

Windows 8 C#调用C++编写的Windows运行时组件
 
#include "pch.h"
#include "WinRTComponent.h"

using namespace CppWinRTComponentDll2;

int CalculatorSample::Add(int x, int y)
{
    return x+y;
}
Windows 8 C#调用C++编写的Windows运行时组件

 头文件

Windows 8 C#调用C++编写的Windows运行时组件
 
#pragma once

using namespace Windows::Foundation;

namespace CppWinRTComponentDll2
{

    public ref class CalculatorSample sealed
    {
    public:
        int Add(int x, int y);

    };
}
 
Windows 8 C#调用C++编写的Windows运行时组件

在C#编写的项目中调用Windows运行时组件的C++方法

添加Windows运行时组件

Windows 8 C#调用C++编写的Windows运行时组件

UI部分

Windows 8 C#调用C++编写的Windows运行时组件
 
<Page
    x:Class="TestWinRTCSDemo.MainPage"
    IsTabStop="false"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TestWinRTCSDemo"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel>
            <TextBox x:Name="txtX" HorizontalAlignment="Center" Height="45" Width="258"></TextBox>
            <TextBlock   Text="+" HorizontalAlignment="Center"  Height="45" Width="258" FontSize="14" FontWeight="Bold"/>
            <TextBox x:Name="txtY" HorizontalAlignment="Center" Height="45" Width="258"></TextBox>
            <Button Content="调用WinRT方法来相加" HorizontalAlignment="Center" Click="Button_Click_1" ></Button>
            <TextBox x:Name="txtAddResult" HorizontalAlignment="Center" Height="45" Width="258"/>
        </StackPanel>
    </Grid>
</Page>
 
Windows 8 C#调用C++编写的Windows运行时组件

C#代码部分

  运行的效果

Windows 8 C#调用C++编写的Windows运行时组件

原文地址


本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2012/07/10/2584129.html,如需转载请自行联系原作者