C++和C#IoT-C++项目访问另一个项目中的C#DLL

C++ and C# IoT - C++ project access C# DLLs in another project

本文关键字:项目 C#DLL 另一个 访问 C#IoT-C++ C++      更新时间:2023-10-16

我正在尝试用C++制作一个Windows IoT应用程序,在那里我也可以使用C#代码。

我首先用Visual C++Blank Windows IoT核心控制台应用程序创建了一个解决方案。这是入口点中的代码:

// EnterPoint.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include "pch.h"
#using <MainLogic.dll>
int main(int argc, char **argv)
{
    int result = MainLogic::StartupTask::Start();
    std::cout << result << "n";
}

然后,我在同一解决方案中创建了另一个名为MainLogic的项目,这次是一个使用.NET Framework 6和默认目标以及Windows Phone 8.1的Visual C#类库(可移植)。这是我制作的C#文件中的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MainLogic
{
    public class StartupTask
    {
        public static int Start()
        {
            return 0;
        }
    }
}

我构建了C#项目,并使用C++项目的目录将..MainLogicbinDebug添加到引用目录和C/C++->Additional#中。

当我在x86体系结构的本地Windows调试器上运行此程序时,它给出了一个错误:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'MainLogic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
   at main(Int32 argc, SByte** argv)
   at _mainCRTStartup()

在生成的命令提示符窗口中。它促使我崩溃,我做到了。窗口上写着:

Unhandled exception at 0x75613E28 (KernelBase.dll) in PythonInCSharpInCPP.exe: 0xE0434352 (parameters: 0x80070002, 0x00000000, 0x00000000, 0x00000000, 0x72D60000).

我转到最后一个地址(0x72D60000),它周围的某个地方写着"这个程序不能在DOS模式下运行"。

我做错了什么?

您需要在C++中添加C#项目作为依赖项。然后,当您构建C#DLL时,它将被复制到C++输出目录中。

0x72D60000地址是加载DLL的基地址。每个windows程序都以一个存根开始,该存根表示它不能在DOS模式下运行,以便在MS-DOS与windows一起运行的时候使用。在Windows下运行时会跳过该部分。