Archief - [PROG][C#->VB.NET] Functie vertalen van C# naar VB.Net

Het archief is een bevroren moment uit een vorige versie van dit forum, met andere regels en andere bazen. Deze posts weerspiegelen op geen enkele manier onze huidige ideeën, waarden of wereldbeelden en zijn op sommige plaatsen gecensureerd wegens ontoelaatbaar. Veel zijn in een andere tijdsgeest gemaakt, al dan niet ironisch - zoals in het ironische subforum Off-Topic - en zouden op dit moment niet meer gepost (mogen) worden. Toch bieden we dit archief nog graag aan als informatiedatabank en naslagwerk. Lees er hier meer over of start een gesprek met anderen.

dieterm

Legacy Member
Hallo,

Ik heb een stukje code in C# dat ik wil vertalen om te gebruiken met VB.NET. De code is afkostig van een programma om met een PIC18F... microcontroller te communiceren.
Het probleem is dat ik niet weet hoe ik de dingen die pointers gebruiken moet vertalen.

Alle tips en uitleg zijn welkom.

Dieter

Code:
using System;

using System.Runtime.InteropServices;

using PVOID = System.IntPtr;
using DWORD = System.UInt32;


namespace usb_api
{
	unsafe public class usb_interface
	{
		#region  String Definitions of Pipes and VID_PID
        //USB\VID_04D8&PID_000C\5&1DAAE7BB&0&2

		//string vid_pid_boot= "vid_04d8&pid_000b";    // Bootloader vid_pid ID
        string vid_pid_norm = "vid_04d8&pid_000c"; //vid_04d8&pid_000c|

		string out_pipe= "\\MCHP_EP1"; // Define End Points
		string in_pipe= "\\MCHP_EP1";
		#endregion

		#region Imported DLL functions from mpusbapi.dll
		[DllImport("mpusbapi.dll")]
		private static extern DWORD _MPUSBGetDLLVersion();
		[DllImport("mpusbapi.dll")]
		private static extern DWORD _MPUSBGetDeviceCount(string pVID_PID);
		[DllImport("mpusbapi.dll")]
		private static extern void* _MPUSBOpen(DWORD instance,string pVID_PID,string pEP,DWORD dwDir,DWORD dwReserved);
		[DllImport("mpusbapi.dll")]
		private static extern DWORD _MPUSBRead(void* handle,void* pData,DWORD dwLen,DWORD* pLength,DWORD dwMilliseconds);
		[DllImport("mpusbapi.dll")]
		private static extern DWORD _MPUSBWrite(void* handle,void* pData,DWORD dwLen,DWORD* pLength,DWORD dwMilliseconds);
		[DllImport("mpusbapi.dll")]
		private static extern DWORD _MPUSBReadInt(void* handle,DWORD dwLen,DWORD* pLength,DWORD dwMilliseconds);
		[DllImport("mpusbapi.dll")]
		private static extern bool _MPUSBClose(void* handle);
		#endregion

		void* myOutPipe;
		void* myInPipe;

		private void OpenPipes()
		{
			DWORD selection=0; // Selects the device to connect to, in this example it is assumed you will only have one device per vid_pid connected.

			myOutPipe = _MPUSBOpen(selection,vid_pid_norm,out_pipe,0,0);
			myInPipe = _MPUSBOpen(selection,vid_pid_norm,in_pipe,1,0);
		}
		private void ClosePipes()
		{
			_MPUSBClose(myOutPipe);
			_MPUSBClose(myInPipe);
		}

		private DWORD SendReceivePacket(byte* SendData, DWORD SendLength, byte* ReceiveData, DWORD *ReceiveLength)
		{
			uint SendDelay=1000;
			uint ReceiveDelay=1000;

			DWORD SentDataLength;
			DWORD ExpectedReceiveLength = *ReceiveLength;

			OpenPipes();

				if(_MPUSBWrite(myOutPipe,(void*)SendData,SendLength,&SentDataLength,SendDelay)==1)
				{

					if(_MPUSBRead(myInPipe,(void*)ReceiveData, ExpectedReceiveLength,ReceiveLength,ReceiveDelay)==1)
					{
						if(*ReceiveLength == ExpectedReceiveLength)
						{
							ClosePipes();
							return 1;   // Success!
						}
						else if(*ReceiveLength < ExpectedReceiveLength)
						{
							ClosePipes();
							return 2;   // Partially failed, incorrect receive length
						}
					}
				}
			ClosePipes();
			return 0;  // Operation Failed
		}

		public DWORD GetDLLVersion()
		{
			return _MPUSBGetDLLVersion();
		}
		public DWORD GetDeviceCount(string Vid_Pid)
		{
			return _MPUSBGetDeviceCount(Vid_Pid);
		}

		public int UpdateLED(uint led, bool State)
		{
			// The default demo firmware application has a defined application
			// level protocol.
			// To set the LED's, the host must send the UPDATE_LED
			// command which is defined as 0x32, followed by the LED to update,
			// then the state to chance the LED to.
			//
			// i.e. <UPDATE_LED><0x01><0x01>
			//
			// Would activate LED 1
			//
			// The receive buffer size must be equal to or larger than the maximum
			// endpoint size it is communicating with. In this case, it is set to 64 bytes.

			byte* send_buf=stackalloc byte[64];
			byte* receive_buf=stackalloc byte[64];

			DWORD RecvLength=3;
			send_buf[0] = 0x32;			//Command for LED Status  
			send_buf[1] = (byte)led;
			send_buf[2] = (byte)(State?1:0);
	
			if (SendReceivePacket(send_buf,3,receive_buf,&RecvLength) == 1)
			{
				if (RecvLength == 1 && receive_buf[0] == 0x32)
				{	
					return 0;
				}
				else
				{
					return 2;
				}
			}
			else
			{	
				return 1;
			}
		}

		public uint Add(uint num1, uint num2)
		{
			// The default demo firmware application has a defined application
			// level protocol.
			// To calculate the sum the host must send the DO_SUM
			// command which is defined as 0xEE, followed by the LED to update,
			// then the state to chance the LED to.
			//
			// i.e. <DO_SUM><0x01><0x02>
			//
			// Would return a command
			//
			// <DO_SUM><0x03>
			//
			// Bear in mind no error correction to prevent roll over in the PIC has 
			// been implemented, to keep this example as simple as possible.
			//
			// The receive buffer size must be equal to or larger than the maximum
			// endpoint size it is communicating with. In this case, it is set to 64 bytes.

			byte* send_buf=stackalloc byte[64];
			byte* receive_buf=stackalloc byte[64];

			uint Temp=0;

			DWORD RecvLength=(byte)2;
			send_buf[0] = 0xEE;			//Command for DO_SUM  
			send_buf[1] = (byte)num1;
			send_buf[2] = (byte)num2;
	
			if (SendReceivePacket(send_buf,4,receive_buf,&RecvLength) == 1)
			{
				Temp = receive_buf[1];
			}
			return Temp;
		}
	}

}

dieterm

Legacy Member
Die heb ik al geprobeerd, maar die code werkt niet.
Ik zoek uitleg over hoe ik die pointers moet vertalen etc..

De DLL declaratie heb ik momenteel zo vertaald, maar weet niet of dit juist is:

Code:
Imports DWORD = System.UInt32
Imports PVOID = System.IntPtr

#Region "Imported DLL Functions from mpusbapi.dll"
    Private Declare Function _MPUSBGetDLLVersion Lib "mpusbapi.dll" () As DWORD

    Private Declare Function _MPUSBGetDeviceCount Lib "mpusbapi.dll" (ByVal pVID_PID As String) As DWORD

    Private Declare Function _MPUSBOpen Lib "mpusbapi.dll" (ByVal instance As DWORD, ByVal pVID_PID As String, ByVal pEP As String, ByVal dwDir As DWORD, ByVal dwReserved As DWORD) As PVOID

    Private Declare Function _MPUSBRead Lib "mpusbapi.dll" (ByVal handle As PVOID, ByVal pData As PVOID, ByVal dwLen As DWORD, ByVal pLength As DWORD, ByVal dwMilliseconds As DWORD) As DWORD

    Private Declare Function _MPUSBWrite Lib "mpusbapi.dll" (ByVal handle As PVOID, ByVal pData As PVOID, ByVal dwLen As DWORD, ByVal pLength As DWORD, ByVal dwMilliseconds As DWORD) As DWORD

    Private Declare Function _MPUSBReadInt Lib "mpusbapi.dll" (ByVal handle As PVOID, ByVal dwLen As DWORD, ByVal pLength As DWORD, ByVal dwMilliseconds As DWORD) As DWORD

    Private Declare Function _MPUSBClose Lib "mpusbapi.dll" (ByVal handle As PVOID) As Boolean

#End Region

dieterm

Legacy Member
Ik heb nog wat opzoekwerk verricht en heb het uiteindelijk succesvol kunnen vertalen. Hopelijk is dit van enig nut voor mensen die met een PIC18F... microcontroller aan het experimenteren zijn en VB.NET willen gebruiken.:

Code:
Imports System
Imports System.Runtime.InteropServices

Imports DWORD = System.UInt32
Imports PVOID = System.IntPtr

Public Class USB_Interface
    Private vid_pid_norm As String

    Public Sub New(Optional ByVal target_vid_pid_norm As String = "vid_04d8&pid_000c")
        Me.vid_pid_norm = target_vid_pid_norm
    End Sub

#Region "Imported DLL Functions from mpusbapi.dll"
    Private Declare Function _MPUSBGetDLLVersion Lib "mpusbapi.dll" () As DWORD

    Private Declare Function _MPUSBGetDeviceCount Lib "mpusbapi.dll" (ByVal pVID_PID As String) As DWORD

    Private Declare Function _MPUSBOpen Lib "mpusbapi.dll" (ByVal instance As DWORD, ByVal pVID_PID As String, ByVal pEP As String, ByVal dwDir As DWORD, ByVal dwReserved As DWORD) As PVOID

    Private Declare Function _MPUSBRead Lib "mpusbapi.dll" (ByVal handle As PVOID, ByVal pData As PVOID, ByVal dwLen As DWORD, ByVal pLength As PVOID, ByVal dwMilliseconds As DWORD) As DWORD

    Private Declare Function _MPUSBWrite Lib "mpusbapi.dll" (ByVal handle As PVOID, ByVal pData As PVOID, ByVal dwLen As DWORD, ByVal pLength As PVOID, ByVal dwMilliseconds As DWORD) As DWORD

    Private Declare Function _MPUSBReadInt Lib "mpusbapi.dll" (ByVal handle As PVOID, ByVal dwLen As DWORD, ByVal pLength As PVOID, ByVal dwMilliseconds As DWORD) As DWORD

    Private Declare Function _MPUSBClose Lib "mpusbapi.dll" (ByVal handle As PVOID) As Boolean
#End Region

    Dim myOutPipe As PVOID
    Dim myInPipe As PVOID

    Public Function GetDLLVersion() As UInt32
        Return _MPUSBGetDLLVersion()
    End Function

    Public Sub OpenPipes(Optional ByVal instance As UInt32 = 0, Optional ByVal in_pipe As String = "\MCHP_EP1", Optional ByVal out_pipe As String = "\MCHP_EP1")
        myOutPipe = _MPUSBOpen(instance, vid_pid_norm, out_pipe, 0, 0)
        myInPipe = _MPUSBOpen(instance, vid_pid_norm, in_pipe, 1, 0)
    End Sub

    Public Sub ClosePipes()
        _MPUSBClose(myOutPipe)
        _MPUSBClose(myInPipe)
    End Sub

    Public Function GetDeviceCount() As DWORD
        Return _MPUSBGetDeviceCount(Me.vid_pid_norm)
    End Function

    Public Function WriteToPic(ByVal data As Byte()) As Boolean
        OpenPipes()
        Dim result As Boolean = Write(data)
        ClosePipes()
        Return result
    End Function

    Public Function ReadFromPic() As Byte()
        OpenPipes()
        Dim data() As Byte = Read()
        ClosePipes()
        Return data
    End Function

    Private Function Write(ByVal data As Byte()) As Boolean
        Dim result As DWORD
        Dim sendLength As IntPtr = Marshal.AllocHGlobal(4)
        Dim ptrData As IntPtr = Marshal.AllocHGlobal(data.Length)

        For i As Integer = 0 To data.Length - 1
            Marshal.WriteByte(ptrData, i, data(i))
        Next

        result = _MPUSBWrite(myOutPipe, ptrData, CUInt(data.Length), sendLength, 1000)

        If result = 1 And Marshal.ReadInt32(sendLength) = data.Length Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Function Read() As Byte()
        Dim ptrData As IntPtr = Marshal.AllocHGlobal(64)
        Dim result As DWORD = Marshal.AllocHGlobal(4)
        Dim ptrBytesRead As IntPtr = Marshal.AllocHGlobal(4)

        result = _MPUSBRead(myInPipe, ptrData, 64, ptrBytesRead, 100)

        Dim bytesRead As DWORD = Marshal.ReadInt32(ptrBytesRead)

        If bytesRead > 0 Then
            Dim tmpData(bytesRead - 1) As Byte

            For i As Integer = 0 To bytesRead - 1
                tmpData(i) = Marshal.ReadByte(ptrData, i)
            Next

            Return tmpData
        Else
            Return Nothing
        End If
    End Function

    Public Function ReadAndWritePic(ByVal writeData() As Byte) As Byte()
        OpenPipes()
        Write(writeData)
        Dim recievedData() As Byte = Read()
        ClosePipes()
        Return recievedData
    End Function
End Class

pascalbianca

Legacy Member
Het is een hele late reactie betreft dit onderwerp , maar heb je dit project nog compleet in VB.Net code en niet C# waar het orginele project uit bestaat?
Toevallig ben ik ook met dit project bezig maar krijg het ondanks jouw bijdrage niet goed aan het lopen omdat niet alle codes van het project hierboven zijn vermeld.

MVg.

Moto

Legacy Member
Waarom niet C# code in een dll steken en die vanuit VB.net gebruiken?

woony

Legacy Member
ik zou ook Moto z'n manier gebruiken. Zet die in een .dll en roep de functies aan vanuit vb, met vb dan. Is toch de makkelijkste oplossing voor dit?.
Het archief is een bevroren moment uit een vorige versie van dit forum, met andere regels en andere bazen. Deze posts weerspiegelen op geen enkele manier onze huidige ideeën, waarden of wereldbeelden en zijn op sommige plaatsen gecensureerd wegens ontoelaatbaar. Veel zijn in een andere tijdsgeest gemaakt, al dan niet ironisch - zoals in het ironische subforum Off-Topic - en zouden op dit moment niet meer gepost (mogen) worden. Toch bieden we dit archief nog graag aan als informatiedatabank en naslagwerk. Lees er hier meer over of start een gesprek met anderen.
Terug
Bovenaan