简体   繁体   中英

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

I have a problem with invoking a few functions from DLL (SDK of some camera). In source of .dll, there is function:

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

and I am trying to call it from .Net console app with following code:

[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();

}

i get following error:

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 passes fine but i cant get anything else. I tried dozen of solutions and I'm getting nowhere.

Here is source of dll and source of my .Net app. Thanks!

[edit]

As @david pointed out, CallingConvention was wrong and now, i get following error:

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.

Is this error from DLL or CLR (.Net)? I never imported any functions from DLL to .Net, so any help is appreciated.

From the unmanaged source:

#define CALL_METHOD __stdcall

And from the managed source:

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

Your calling conventions do not match.


As for the edit to the question, that is presumably because the C# struct definition does not match the unmanaged struct. You have failed to translate any of the arrays correctly. They will require the use of [MarshalAs(UnmanagedType.ByValArray, SizeConst=...)] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM