你能在UWP的C#代码中使用C++ DLL吗?

M35*_*579 4 c# c++ python dll uwp

我在Visual Studio中编写了一个C++类库,它只定义了一个调用Python的函数:

#pragma once

#include <Python.h>

extern "C"
__declspec(dllexport)
void python()
{
    Py_Initialize();
    PyRun_SimpleString("2 + 2");
}
Run Code Online (Sandbox Code Playgroud)

我在同一个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();
        }

        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

该应用程序处于发布配置中.

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

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'.
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:我可以从C#UWP项目中引用C++类库吗?或者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))
Run Code Online (Sandbox Code Playgroud)

我添加了一个用户到DLL的对象名称"Everyone"(我不知道如何给予每个人权限),但错误仍然出现.

Fan*_*SFT 10

首先,UWP不能仅通过DLLImport使用传统的C++ DLL.

如果要将旧的c ++函数公开给C#,第一个建议是使用WinRT组件包装该C++逻辑.然后,您可以通过以下步骤在UWP应用程序中引用此组件:将其添加到项目中,在"解决方案资源管理器"窗口中打开文件的属性,并将它们标记为要包含在应用程序包中的内容.这篇文章会有所帮助.这个提供了更详细的步骤.

如果你想PInvoke dll,你可以按照这些步骤(你可以参考这篇MSDN帖子):

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

  2. 然后在适当的cs文件中,使用DllImport来PInvoke dll.

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