在 C# 中调用 C++ dll 时找不到入口点

Unable to find an entry point when calling C++ dll in C#

本文关键字:找不到 入口 dll C++ 调用      更新时间:2023-10-16

我正在尝试学习 P/Invoke,所以我在 C++ 中创建一个简单的 dll

KingFucs.h:

namespace KingFuncs
{
    class KingFuncs
    {
    public:
        static __declspec(dllexport) int GiveMeNumber(int i);
    };
}

金趣.cpp:

#include "KingFuncs.h"
#include <stdexcept>
using namespace std;
namespace KingFuncs
{
    int KingFuncs::GiveMeNumber(int i)
    {
        return i;
    }
}

所以它确实编译了,然后我用代码将此 dll 复制到我的 WPF 的调试文件夹中:

[DllImport("KingFuncDll.dll", EntryPoint = "GiveMeNumber", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern int GiveMeNumber(
              int i
              );

并在按钮单击中调用它:

private void Button_Click(object sender, RoutedEventArgs e)
{
    int num = GiveMeNumber(123);
}

但它给了我例外:

无法在 DLL 中找到名为"GiveMeNumber"的入口点 "金方.dll"。

真。。。。我做错了什么...它显然能够找到DLL,否则将是另一个例外。 但是我的方法名称完全相同。我想不出其他原因。

导出

函数时需要使用extern "C",以便禁止C++名称重整。而且你也不应该尝试对类的成员进行p/调用。请改用免费函数:

extern "C" {
    __declspec(dllexport) int GiveMeNumber(int i)
    {
        return i;
    }
}

在托管端,您的DllImport属性都是错误的。不要使用仅适用于 Win32 API 的SetLastError。如果没有文本参数,请不要费心设置CharSet。无需ExactSpelling.并且调用约定大概是Cdecl.

[DllImport("KingFuncDll.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int GiveMeNumber(int i);

问题是你在C++类中声明C++"函数",并告诉 P/Invoke 使用 StdCall。

尝试在类外部声明一个C++函数,然后像你一样导出它。然后你的代码应该可以工作了。

如果你真的必须在类中有一个C++函数,看看CallingConvention.ThisCall。但是,您负责创建非托管类实例,并将其作为 P/Invoke 调用的第一个参数传递

dll 文件的入口点名称在 .exp 文件中给出,该文件位于存在其他源文件的调试文件夹中。如果垃圾箱不起作用,您可以尝试此操作。