65.9K
CodeProject 正在变化。 阅读更多。
Home

从非托管 C/C++ 代码调用 C# .NET 方法

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (28投票s)

2013 年 12 月 11 日

CPOL

1分钟阅读

viewsIcon

293969

downloadIcon

12188

描述了如何从非托管 C++ 代码调用 C# .NET 方法,并提供了一个示例。

引言

由于一些我不便在此详述的原因,我需要从非托管代码中使用 C# .NET DLL。我花了很多时间寻找答案,最终才弄清楚。所以我把这个例子发在这里,希望能有所帮助。

其工作原理相当简单,需要三个组件:

  1. 执行任何操作的 C# DLL。
  2. 具有暴露的 C 函数的托管 C++ DLL。该 DLL 将调用你的 C# DLL 方法。 
  3. 将调用托管 C++ DLL 中暴露的 C 函数的非托管 C++ 应用程序/DLL。

使用代码

创建你的 C# DLL。下面的示例只是显示一个简单的 MessageBox,并根据 OKCANCEL 设置值的返回值。

// ManagedClass.cs

// Any source code blocks look like this
//

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ManagedCSharp
{
    public static class ManagedClass
    {
        public static void ShowValue(ref int value)
        {
            DialogResult result = MessageBox.Show("C# Message Box", 
                    "C# Message Box", MessageBoxButtons.OKCancel);

            if (result == DialogResult.OK)
                value = 1;
            else
                value = 2;
            return;
        }
    }
}

创建一个托管 C++ DLL,并在你的 C# 项目中引用它。

这会将你的函数 ShowMessageBox 以非托管格式导出。

在导出的函数内部,调用托管 C++ 方法,该方法调用你的 C# 方法。

// ManagedDll.h

#pragma once

using namespace System;
using namespace System::Reflection;

namespace ManagedDll {    

    public ref class DoWork
    {
        public:void ShowCSharpMessageBox(int *value)
        {            
            ManagedCSharp::ManagedClass::ShowValue(*value);
            return;
        }
    };
}

__declspec(dllexport) void ShowMessageBox(int *value)
{
    ManagedDll::DoWork work;    
    work.ShowCSharpMessageBox(value);    
}

创建你的非托管 C 或 C++ DLL 或 EXE,并调用托管代码中的暴露的 C++ 方法。

在你的非托管项目设置中,你需要在构建时引用由 ManagedDll 项目创建的 ManagedDll.lib 文件。

// TestApp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "conio.h"
#include <iostream>
#include <windows.h>

_declspec(dllexport) void ShowMessageBox(int *value);


int _tmain()
{
    int *result;

    ShowMessageBox(result);

    if(*result == 1)
        printf("Ok Was Pressed \n");
    else
        if(*result == 2)
            printf("Cancel Was Pressed \n");
        else
            printf("Unknown result \n");

    system("pause");

    return 0;
}

查找附加的完整项目,该项目应该可以直接构建。在 Visual Studio 2008 中构建。

© . All rights reserved.