【问题标题】:How to import function from c++ dll如何从 c++ dll 中导入函数
【发布时间】:2021-10-08 16:49:37
【问题描述】:

这里是c++ dll代码:

#include<stdlib.h>
#include "pch.h"

extern "C" _declspec(dllexport) int Add(int a, int b)
{
    return a + b;
}

我在 Visual Studio 中运行的 C# 代码:

[DllImport(@"C:\Dll1.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int port, int speed);

public static void Main()
{
    int res = Add(8, 11);
    Console.WriteLine(res);

}

没问题,输出:19

PowerShell 代码:

Add-Type -Name MyFunctions -Namespace Cpp @'
[DllImport(@"C:\Dll1.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int port, int speed);
'@

[Cpp.MyFunctions]::Add(8, 11)

输出: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

但是从 user32.dll/kernel32.dll 导入的函数没有任何问题。

如何解决?

【问题讨论】:

    标签: c# c++ .net powershell


    【解决方案1】:

    确保您将 32 位 dll 用于 32 位 powershell 进程,将 64 位 dll 用于 64 位 powershell 进程。 该错误看起来就像您尝试将 32 位 dll 加载到 64 位进程中一样。请注意,编译为“任何 CPU”的 .net 应用程序将默认以 32 位模式运行,即使在 64 位操作系统上也是如此。

    更新

    如果你有你的 dll 的源代码,那么你应该为 64 位环境重新编译它,然后导入这个 64 位版本。

    如果您需要在 32 位和 64 位 powerShell 环境中执行 PS 脚本,那么您应该部署两个版本的 dll 并在运行时选择正确的版本。我不知道如何为 PS 做到这一点,但对于 C# 解决方案,您可以使用基于 #ifdef 的解决方案,如下所述:Using a 32bit or 64bit dll in C# DllImport

    如果您没有 dll 的来源,那么一切都会变得复杂,我不知道这里有什么直接的解决方案。您可以尝试将您的 DLL 包装在 32 位进程内(甚至进程外)COM 服务器中(借助 C# 或 C++),然后将此服务器与 New-Object 一起使用。据我所知,Windows 有特殊的 shims 允许从 64 位进程使用 32 位 COM 对象,反之亦然,但我不确定这是否适用于 PS。

    对于内置 DLL,Windows 具有从 System32 到 SysWOW64 的自动文件路径重定向。因此,当您请求 user32 导入时,您将获得不同的 user32 库,具体取决于您的进程位数。您可以在此处阅读更多信息:64bit PowerShell calls the 32bit DLL

    【讨论】:

    • 好,你说得对,这段代码可以在 PowerShell (x86) 上运行。但 user32.dll 在 32 位和 64 位 PowerShell 中工作。如何让我的 dll 也可以在任何 Powershell(32 和 64)上运行?
    • @Danny 编译您的 DLL 的 32 位版本和 64 位版本,然后根据运行时位数分别导入和 hide them behind a common method that decides which one to call
    • @Danny,我更新了帐户可能解决方案的答案。
    猜你喜欢
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多