gpt4 book ai didi

c# - 使用 DlImport、Entrypoint 从 C# 调用命名空间中的 C++ 函数

转载 作者:可可西里 更新时间:2023-11-01 14:14:53 28 4
gpt4 key购买 nike

我已经阅读了几个与我相关的问题,但没有一个对我有用。

我需要从非托管 DLL 调用函数。我在 SysWow64 中有 DLL 的 32 位版本,在 system32 中有 64 位版本。无论如何,我正在为 x86 编译。我没有 DLL 的源代码,因此无法使用 extern "C"重新编译。

DLL 包含文件的相关部分:

(...)
#include <string>
namespace SomeNamespace
{
(...)
typedef std::wstring STRING;
(...)
class SomeClass
{
(...)
static bool SomeFunc(const STRING& p1, bool p2);
(...)
}
}

调用 SomeFunc 时出现异常:“找不到名为‘?’的入口点在 DllName.dll 中”(翻译是我的,可能不准确)。

我在 C# 中的声明:

    [System.Runtime.InteropServices.DllImport("DllName.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "?SomeFunc@SomeClass@SomeNamespace@@SA_NABV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@_N@Z")]
bool SomeFunc(string p1, bool p2);

我也试过以下方法:

[System.Runtime.InteropServices.DllImport("DllName.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "#15")]
bool SomeFunc(string p1, bool p2);

15是根据Depends的函数序号,第一个版本中的EntryPoint也是从Depends中获取的。

根据undname.exe,这是函数的原始声明:

public: static bool __cdecl SomeFunc(class ?? :: ?? ::Z::basic_string<wchar_t,str
uct std::char_traits<wchar_t>,class w::allocator<wchar_t>,td,bool> const &, ?? )
throw( ?? )

它似乎没有正确解析它; bool 应该是 FuncName 的参数,而不是 basic_string 的类型参数。但是,我不确定这只是 undname.exe 的解析错误还是更严重的问题。

我该如何解决?

更新:当使用函数的序号作为入口点时,我没有得到异常。我从 Form 的 Load 事件中调用它,在调试时,我失去了控制权。我的意思是,我正在调试 SomeFunc() 行上的光标,我按 F10,应用程序继续运行,就好像我没有调试一样。我没有收到 ThreadException 或 UnhandledException。

调用代码:

public bool CallSomeFunc()
{
try
{
SomeFunc("p1", true);
}
catch (Exception ex)
{
ex.ToString(); // I just use this to put a breakpoint while debugging.
}
return true;
}

结束更新

最佳答案

您需要 C++/CLI 作为包装器来从 C++ 类中调用方法。PInvoke 仅适用于全局导出函数。

看看C++/CLI wrapper for native C++ to use as reference in C# .

关于c# - 使用 DlImport、Entrypoint 从 C# 调用命名空间中的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18075261/

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