c# - P/在 C# 中从 C++ dll 调用 DLL 函数

标签 c# c++ .net dll pinvoke

我在从 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 是我的 .Net 应用程序的 dll 和 source 的来源。谢谢!

[编辑]

正如@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=...)]

关于c# - P/在 C# 中从 C++ dll 调用 DLL 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28025221/

相关文章:

c# - 如何在工厂中使用通用接口(interface)

c++ - 通过运算符重载写入映射的内容

c++ - 浮点异常、段错误和类似错误

asp.net - 在 Net Framework 上编写的应用程序中使用 WinHttpHandler 与 HttpClientHandler

c# - 显式和隐式 C#

c# - 无法从字符串转换为 System.Diagnostics.ProcessStartInfo C#

c# - Console.Out 输出显示在输出窗口中,需要在 AllocConsole() 中

c++ - 对于基于指针和数组的字符串初始化,strlen 和 sizeof 的不同答案

c# - 如何使用 zlib.NET 扩充文件?

c# - Perforce .net API 直接从服务器/连接超时下载文件