4

I have read several questions related to mine, but none of the multiple answers worked for me.

I need to call a function from an unmanaged DLL. I have the 32 bit version of the DLL in SysWow64 and the 64 bit version in system32. Anyway, I am compiling for x86. I don't have the source for the DLL, so recompiling with extern "C" is not an option.

The relevant parts of the include file for the DLL:

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

When calling SomeFunc, I am getting an exception: "Can't found the entry point named '?' in DllName.dll" (translation is mine, could be inexact).

My declaration in 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);

I have also tried the following:

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

15 is the function ordinal according to Depends, and the EntryPoint in the first version is also obtained from Depends.

According to undname.exe, this is the original declaration of the function:

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( ?? )

It doesn't seem to be parsing it correctly; the bool should be a parameter for FuncName, not a type parameter for basic_string. However, I'm not sure if this is just a parsing error from undname.exe or something more serious.

How can I fix it?

Update: When using the ordinal of the function as entry point, I don't get an exception. I am calling this from the Load event of a Form, and when debugging, I lost the control. I mean, I am debugging with the cursor on the SomeFunc() line, I hit F10, and the app continues as if I wasn't debugging. I don't get a ThreadException or an UnhandledException.

The calling code:

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

End Update

4

1 回答 1

3

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

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

于 2013-08-06T08:46:41.580 回答