gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:18 29 4
gpt4 key购买 nike

我在 Visual Studio 中编写了一个 C++ 类库,它只定义了一个调用某些 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++ 类库吗?还是 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))

我在 DLL 中添加了一个对象名为“Everyone”的用户(我不确定如何给每个人权限)但错误仍然出现。

最佳答案

首先,UWP 不能仅通过 DLLImport 使用遗留的 C++ dll。

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

如果你想PInvoke这个dll,你可以按照以下步骤操作(你可以引用这个MSDN post):

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

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

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

关于c# - 您可以在 UWP 中的 C# 代码中使用 C++ DLL 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33489924/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com