您可以在 UWP 中的 C# 代码中使用 C++ DLL 吗?

Can you use C++ DLLs in C# code in a UWP?

我在 Visual Studio 中写了一个 C++ Class 库,它只定义了一个调用某些 Python:

的函数
#pragma once

#include <Python.h>

extern "C"
__declspec(dllexport)
void python()
{
    Py_Initialize();
    PyRun_SimpleString("2 + 2");
}

我在同一解决方案中创建了另一个项目,该项目是 C# Blank Universal 应用程序。我试图引用我之前提到的项目生成的 DLL:

using System;
...

namespace StartupApp
{
    ...
    sealed partial class App : Application
    {
        private const string CPPPythonInterfaceDLL = @"pathtodll";

        [DllImport(CPPPythonInterfaceDLL, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
        private static extern void python();

        public static void Python()
        {
            python();
        }
        ...
        public App()
        {
            ...

            Python();
        }

        ...
    }
}

该应用处于发布配置中。

每当我尝试 运行 我的本地计算机上的应用程序时,它总是给出错误:

The program '[2272] StartupApp.exe' has exited with code -1073741790 (0xc0000022).
Activation of the Windows Store app 'ab6a8ef2-1fa8-4cc7-b7b3-fb7420af7dc3_7dk3a6v9mg4g6!App' failed with error 'The app didn't start'.

所以我的问题是:我可以从 C# UWP 项目中引用 C++ class 库吗?还是 UWP 应用程序的安全性不允许这样做?

还是因为Python.h?

编辑:

我用一个 DLL 项目和一个包装它的运行时组件构建了这个项目,现在我遇到了这个错误:

“系统”类型的异常

'System.DllNotFoundException' occurred in StartupApp.exe but was not handled in user code

Additional information: Unable to load DLL 'pathtodll': Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

我用对象名称 "Everyone" 向 DLL 添加了一个用户(我不确定如何给每个人权限)但错误仍然出现。

首先,UWP 无法仅通过 DLLImport 使用旧版 C++ dll。

如果您想向 C# 公开旧版 c++ 函数,第一个建议是使用 WinRT 组件包装该 C++ 逻辑。然后您可以通过以下步骤在 UWP 应用程序中引用该组件:将其添加到项目中,在解决方案资源管理器中打开文件的属性 window,并将它们标记为要包含在应用程序包中的内容。 This post would be helpful. This one 提供了更详细的步骤。

如果要PInvoke dll,可以按照以下步骤操作(可以参考这个MSDN post):

  1. 将 win32 dll 添加到您的 UWP 项目中,确保将其类型设置为 'content'

  2. 然后在正确的cs文件中,使用DllImport来PInvoke dll。

还有一件事:您需要确保您的 Python dll 没有在 WinRT 中使用禁止的 API。您可以使用 dll 的 /ZW 编译选项来检查这一点。