P/invoke C# 中来自 C++ dll 的 DLL 函数

P/invoke DLL functions from C++ dll in C#

我在从 DLL(某些相机的 SDK)中调用一些函数时遇到问题。在.dll的源码中,有函数:

NET_SDK_API LONG CALL_METHOD NET_SDK_Login(char *sDVRIP,WORD wDVRPort,char *sUserName,char *sPassword,LPNET_SDK_DEVICEINFO lpDeviceInfo);

我正在尝试使用以下代码从 .Net 控制台应用程序调用它:

[STAThread]
static void Main(string[] args)
{
    long userid = 0;

    _net_sdk_deviceinfo dinfo = new _net_sdk_deviceinfo();
    short port = 6036;

    try
    {

        if (DVR.NET_SDK_Init())
        {
            Console.WriteLine("ok");
            userid = DVR.NET_SDK_Login("192.168.1.132", port, "admin", "123456", out dinfo);
            userid.ToString();
        }
        else
        {
            Console.WriteLine("err");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    Console.ReadKey();

}

我收到以下错误:

A call to PInvoke function 'DVRtest!DVRtest.DVR::NET_SDK_Login' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

Init 顺利通过,但我无法获得任何其他信息。我尝试了很多解决方案,但我一无所获。

Here is source of dll and source 我的 .Net 应用程序。谢谢!

[编辑]

正如@david 指出的那样,CallingConvention 是错误的,现在,我收到以下错误:

The runtime has encountered a fatal error. The address of the error was at 0x6fda02c7, on thread 0x2554. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

这个错误是来自 DLL 还是 CLR (.Net)?我从未将任何函数从 DLL 导入到 .Net,因此非常感谢您的帮助。

来自非托管来源:

#define CALL_METHOD __stdcall

来自受管理的来源:

[DllImport("DVR_NET_SDK.dll", CallingConvention = CallingConvention.Cdecl)]

您的调用约定不匹配。


至于对问题的编辑,这大概是因为 C# 结构定义与非托管结构不匹配。您未能正确翻译任何数组。他们将需要使用 [MarshalAs(UnmanagedType.ByValArray, SizeConst=...)].