我正在VB.NET项目中使用C ++ DLL。
我成功调用了一些DLL函数,但是如果调用返回C ++结构指针的函数,则会出现此错误:
试图读取或写入受保护的内存。这通常表明其他内存已损坏。
也许我没有在VB中创建正确的结构,您能帮我吗?
这就是我在VB中声明和调用函数的方式:
<System.Runtime.InteropServices.DllImport("MobilePosAdapterCLib.dll", CallingConvention:=CallingConvention.Cdecl, SetLastError:=False)>
Public Shared Function MobilePosAdapter_getLastTransactionResult() As System.IntPtr
End Function
Dim risultato As System.IntPtr
Dim risultato2 As PaymentResult
risultato = MobilePosAdapter_getLastTransactionResult()
risultato2 = Marshal.PtrToStructure(risultato, GetType(PaymentResult)) ' error here
这是c ++结构:
typedef struct {
char text[48 + 1];
int attribute;
} ReceiptRow;
typedef struct {
int numReceiptRows;
int signatureRequired;
ReceiptRow rows[200];
} Receipt;
typedef struct {
int operationType;
char posId[32 + 1];
char terminalId[8 + 1];
char transactionId[10 + 1];
int transactionResult;
char transactionDate[8 + 1];
char transactionTime[9 + 1];
char stan[6 + 1];
int isReceiptPresent;
Receipt receipt;
} TransactionResult;
typedef struct {
TransactionResult base;
int amount;
char pan[19 + 1];
int cardType;
int technologyType;
char acquirerId[11 + 1];
char acquirerName[16 + 1];
char approvalCode[6 + 1];
char merchantId[15 + 1];
char actionCode[3 + 1];
char posMessage[16 + 1];
char emvApplicationId[32 + 1];
} PaymentResult;
这是我的VB.NET结构:
Public Structure ReceiptRow
Public text As Char()
' tried also so:
'<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=48)>
'Public text As String
Public attribute As Integer
End Structure
Public Structure Receipt
Public numReceiptRows As Integer
Public signatureRequired As Integer
Public Shared rows() As ReceiptRow = Arrays.InitializeWithDefaultInstances(Of ReceiptRow)(200)
End Structure
Public Structure TransactionResult
Public operationType As Integer
Public posId As Char()
Public terminalId As Char()
Public transactionId As Char()
Public transactionResult As Integer
Public transactionDate As Char()
Public transactionTime As Char()
Public stan As Char()
Public isReceiptPresent As Integer
Public receipt As Receipt
End Structure
Public Structure PaymentResult
Public base As TransactionResult
Public amount As Integer
Public pan As Char()
Public cardType As Integer
Public technologyType As Integer
Public acquirerId As Char()
Public acquirerName As Char()
Public approvalCode As Char()
Public merchantId As Char()
Public actionCode As Char()
Public posMessage As Char()
Public emvApplicationId As Char()
End Structure
更新:
由于GSerg的评论,我设法获得了几乎所有东西,我的最后一个问题是将这部分转换为VB.NET:
typedef struct {
int numReceiptRows;
int signatureRequired;
ReceiptRow rows[200];
} Receipt;
似乎可以使用:
Public Structure Receipt
Public numReceiptRows As Integer
Public signatureRequired As Integer
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=200)>
Public rows As ReceiptRow()
End Structure