在本机C ++项目中导入C#dll库

时间:2016-03-18 12:03:02

标签: c# c++ .net visual-studio visual-studio-2015

我正在尝试将C#dll库包含到Native C ++控制台应用程序中。我正在使用这篇文章: https://support.microsoft.com/en-us/kb/828736#bookmark-7

然而,本文是为Visual Studio 2015编写的,我使用的是Visual Studio 2015。

首先,我在Stackoverflow上检查了几个答案,但这些问题都不是我正在寻找的。

离我最近的问题是: C# library to native C++ application

因此,我创建了一个C#库项目,其中包含以下代码:

namespace Testing_Library
{

    // Interface declaration
    public interface iCalculator
    {
        int Add(int number1, int number2);
    }

    public class ManagedClass:iCalculator
    {
        public int Add(int number1, int number2)
        {
            return number1 + number2;
        }
    }
}

然后我将项目编译为dll文件,然后我通过RegAsm.exe注册了dll文件。现在我有两个输出文件:

  

Testing_Library.dll

  

Testing_Library.tlb

此外,我还创建了Native C ++ Windows控制台应用程序项目。在这个项目中,我有一个带有以下代码的.cpp文件:

// Import the type library.
#import "..\Testing_Library\bin\Debug\Testing_Library.tlb" raw_interfaces_only

using namespace std;
using namespace Testing_Library;

void main()
{
    // Initialize COM.
    HRESULT hr = CoInitialize(NULL);

    // Create the interface pointer.
    iCalculatorPtr pICalc(__uuidof(ManagedClass));

    long lResult = 0;

    // Call the Add method.
    pICalc->Add(5, 10, &lResult);

    wprintf(L"The result is %d", lResult);

    // Uninitialize COM.
    CoUninitialize();

}

当我尝试运行该项目时,我收到以下错误屏幕:

enter image description here

目前我不知道为什么我收到此错误Windows并且我无法在互联网上找到相关信息。请你帮助我好吗? 在这里,您可以找到所有项目的整个解决方案: Onedrive folder

我正在尝试编译并运行当前:

  

Test_me

  

Testing_Library

1 个答案:

答案 0 :(得分:1)

请将项目属性中的平台目标更改为x86以用于.NET程序集。

enter image description here

相关问题