[英]Importing C++ dll to C#
我是C#的新手,請在以下情況下為我提供幫助。
我正在嘗試將C ++ dll導入我的C#代碼,並且出現以下錯誤。
對PInvoke函數'SerialInterface!SerialInterface.Form1 :: ReadTagData'的調用已使堆棧不平衡。 這可能是因為托管PInvoke簽名與非托管目標簽名不匹配。 檢查PInvoke簽名的調用約定和參數是否與目標非托管簽名匹配。
下面是C#代碼
const int buffSize = 33;
const int addr = 112;
const int readBytes = 8;
[DllImport(@"C:\Visual Studio 2010\Projects\SerialInterface\SerialInterface\bin\Debug\AP4600_SDK.dll")]
public static extern int ReadTagData(string tagID, string tagBuffer, Int32 szTagDataBuf, Int32 TagAddress, Int32 nBytes);
string asciiRead = "";
int s = ReadTagData(TagId, asciiRead, buffSize, addr, readBytes);
ReadTagData
中的功能ReadTagData
定義為
AP4600_SDK_API int ReadTagData(
const char *pTagId, /* TagId of tag to be read, from Identify */
char *pTagDataBuf, /* (Output) The data read (ASCII representation of HEX), min size is 2*nBytes+1 (33 for Allegro) */
size_t szTagDataBuf, /* Size of TagDataBuf, minimum is 2*nBytes+1 (33 for Allegro) */
int TagAddress, /* Address of first byte to read */
size_t nBytes /* Number of bytes to read (between 1 and 8, inclusive) */
); /* Returns zero for success, non zero failure */
這是我可以看到的錯誤:
AP4600_SDK_API
的定義方式,調用約定可能是錯誤的。 由於無法看到AP4600_SDK_API
評估方式,因此無法確定。 您可能需要在p / invoke中明確指定調用約定。 目前,它使用默認值CallingConvention.StdCall
。 StringBuilder
而不是`string。 size_t
參數應為指針大小。 使用UIntPtr
。 因此,假設調用約定為StdCall
則它將是:
[DllImport(@"...", CallingConvention.StdCall)] // or perhaps CallingConvention.Cdecl
public static extern int ReadTagData(
string tagID,
StringBuilder tagBuffer,
UIntPtr szTagDataBuf,
int TagAddress,
UIntPtr nBytes
);
這樣稱呼它:
StringBuilder tagBuffer = new StringBuilder(nBytes*2+1)
int retval = ReadTagData(tagId, tagBuffer, tagBuffer.Capacity, addr, nBytes);
if (retval != 0)
// handle error
// output can now be read with tagBuffer.ToString()
在收到的錯誤消息中明確指出了該問題。
char *pTagDataBuf
,c ++中的char *pTagDataBuf
與c#中的string pTagDataBuf
。 C#具有托管字符串。 char*
使用非托管指針。 您可能需要使用不安全的代碼塊來訪問該功能。
如果您嘗試將32位dll加載到64位項目或vica verca中,也會顯示此錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.