簡體   English   中英

將 C++ DLL 導入 C#

[英]Import a C++ DLL into C#

我嘗試在我的 C# 項目中實現 C++ DLL。 我給出了以下頭文件:

#ifdef EBEXPORT
const long EBDECL
#else
const long EBDECL __declspec(dllimport)
#endif

const long EBCALL __stdcall


#if defined (__cplusplus)
extern "C" 
{
#endif

EBDECL long EBCALL EbInitTcp(long nUnit, const char* pIP, long nIPSize);

#if defined (__cplusplus)
}
#endif

這是我用來在 C# 中實現 DLL 的代碼:

using System.Runtime.InteropServices;

namespace NoName
{
    class DLLImport
    {
        [DllImport("C:/lib/host.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern long EbInitTcp(long nUnit, string pIP, long nIPSize);

        public void Init()
        {
            string ip = "192.168.0.1";
            EbInitTcp(1, ip, ip.Length));
        }

    }
}

如果我執行代碼,我會收到PInvokeStackImbalance異常。 請你幫助我好嗎?

驗證您的調用約定; 請注意extern "C"默認為CallingConvention.Cdecl 此錯誤通常是由錯誤的調用約定引起的。

還要注意 C# 的long和 C++ 的long可能不同。

看起來您正在嘗試指定__stdcall ,但這是一個語法錯誤。 在任何情況下,請確保您的調用約定是同步的。

不平衡可能是由大小和類型不匹配的調用約定( cdeclstdcall )或不匹配的函數參數引起的。

C++ 調用約定定義很少見,它通常用#define定義。

#ifdef EBEXPORT
  #define EBDECL __declspec(dllexport)
#else
  #define EBDECL __declspec(dllimport)
#endif

#define EBCALL __stdcall

#if defined (__cplusplus)
extern "C" 
{
#endif

EBDECL const long EBCALL EbInitTcp(long nUnit, const char* pIP, long nIPSize);

#if defined (__cplusplus)
}
#endif

在 C# 方面;

using System.Runtime.InteropServices;

namespace NoName
{
    class DLLImport
    {
        [DllImport("C:/lib/host.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern long EbInitTcp(int nUnit, string pIP, int nIPSize);

        public void Init()
        {
            string ip = "192.168.0.1";
            EbInitTcp(1, ip, ip.Length));
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM