Bu kodu çevirirken nerede hata yapıyorum ?

Delphi'de kod yazma ile ilgili sorularınızı bu foruma yazabilirsiniz.
Cevapla
seci20
Üye
Mesajlar: 228
Kayıt: 25 May 2015 04:39

Bu kodu çevirirken nerede hata yapıyorum ?

Mesaj gönderen seci20 » 09 Şub 2019 06:21

Ustalarım merhaba. Adb protocokolünü kullanarak android cihazlara bağlanmak istiyorum. Yalnız bunu adb.exe kullanamadan yapmak istiyorum. C++ ve python kodu olarak internette var delphiye çeviriyorum ama bir türlü hata vermemesini sağlayamadım.

C++ kodu şu şekilde.


AdbOperator.h

Kod: Tümünü seç

#if !defined(AFX_ADBOPERATOR_H__5DEB1F22_4BE7_4C25_9541_D4F238676DDC__INCLUDED_)
#define AFX_ADBOPERATOR_H__5DEB1F22_4BE7_4C25_9541_D4F238676DDC__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// AdbOperator.h : header file
//

typedef void* ADBAPIHANDLE;

typedef struct _AdbInterfaceInfo {
	/// Inteface's class id (see SP_DEVICE_INTERFACE_DATA for details)
	GUID          class_id;
	
	/// Interface flags (see SP_DEVICE_INTERFACE_DATA for details)
	unsigned long flags;
	
	/// Device name for the interface (see SP_DEVICE_INTERFACE_DETAIL_DATA
	/// for details)
	wchar_t       device_name[1];
} AdbInterfaceInfo;

typedef enum _AdbOpenAccessType {
	/// Opens for read and write access.
	AdbOpenAccessTypeReadWrite,
		
		/// Opens for read only access.
		AdbOpenAccessTypeRead,
		
		/// Opens for write only access.
		AdbOpenAccessTypeWrite,
		
		/// Opens for querying information.
		AdbOpenAccessTypeQueryInfo,
} AdbOpenAccessType;


typedef enum _AdbOpenSharingMode {
	/// Shares read and write.
	AdbOpenSharingModeReadWrite,
		
		/// Shares only read.
		AdbOpenSharingModeRead,
		
		/// Shares only write.
		AdbOpenSharingModeWrite,
		
		/// Opens exclusive.
		AdbOpenSharingModeExclusive,
} AdbOpenSharingMode;

typedef bool (__cdecl *AdbCloseHandle)(ADBAPIHANDLE); 
typedef ADBAPIHANDLE (__cdecl *AdbEnumInterfaces)(GUID,bool,bool,bool); 
typedef bool (__cdecl *AdbNextInterface)(ADBAPIHANDLE,AdbInterfaceInfo*,unsigned long*); 
typedef ADBAPIHANDLE (__cdecl *AdbCreateInterface)(GUID,unsigned short,unsigned short,unsigned char); 
typedef ADBAPIHANDLE (__cdecl *AdbOpenDefaultBulkReadEndpoint)(ADBAPIHANDLE,AdbOpenAccessType,AdbOpenSharingMode);

/////////////////////////////////////////////////////////////////////////////
// AdbOperator window

class AdbOperator
{
// Construction
public:
	AdbOperator();

// Attributes
public:

// Operations
public:
	HMODULE m_hAdbwinapi;
	AdbCloseHandle m_pAdbCloseHandle;
	AdbEnumInterfaces m_pAdbEnumInterfaces;
	AdbNextInterface m_pAdbNextInterface;
	AdbCreateInterface m_pAdbCreateInterface;
	AdbOpenDefaultBulkReadEndpoint m_pAdbOpenDefaultBulkReadEndpoint;

	BOOL InitAdbApi();
	VOID DeInitAdbApi();
	int  ScanAdbDevice();
    BOOL IsAdbDeviceOnline();
    int ExecPackCmd(long nUserdataSize);
    BOOL PullImage(CString strTargetImagePath);
	virtual ~AdbOperator();
    
	// Generated message map functions
protected:
private:
    CString m_strModulePath;
	CString m_strAdbDllePath;
    int Exec(char** bufRawOutput, const CString adbCmd, int nTimeoutCount);
};

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_ADBOPERATOR_H__5DEB1F22_4BE7_4C25_9541_D4F238676DDC__INCLUDED_)
AdbOperator.cpp

Kod: Tümünü seç

// AdbOperator.cpp : implementation file
//

#include "stdafx.h"
#include "FirmwareModifier.h"
#include "AdbOperator.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

extern cmLog *g_pPluginLogObject;
#define ANDROID_USB_CLASS_ID \
{0xf72fe0d4, 0xcbcb, 0x407d, {0x88, 0x14, 0x9e, 0xd6, 0x73, 0xd0, 0xdd, 0x6b}};
static const GUID usb_class_id = ANDROID_USB_CLASS_ID;

/////////////////////////////////////////////////////////////////////////////
// AdbOperator

AdbOperator::AdbOperator()
{
    // Init module path
    GetModuleFileName(NULL, m_strModulePath.GetBuffer(MAX_PATH), MAX_PATH);
    m_strModulePath.ReleaseBuffer();
    m_strModulePath = m_strModulePath.Left(m_strModulePath.ReverseFind(_T('\\'))+1);
	m_strAdbDllePath = m_strModulePath.Left(m_strModulePath.ReverseFind(_T('\\'))+1)+_T("bin\\");
}

AdbOperator::~AdbOperator()
{
}

BOOL AdbOperator::InitAdbApi()
{
	g_pPluginLogObject->Record(_T("%s"),m_strAdbDllePath+ _T("AdbWinApi.dll"));
	if (!PathFileExists(m_strAdbDllePath + _T("AdbWinApi.dll")))
	{
		CString strSysDir=_T("");
		GetWindowsDirectory(strSysDir.GetBuffer(MAX_PATH),MAX_PATH);
		strSysDir.ReleaseBuffer();
		if (strSysDir.IsEmpty())
		{
			strSysDir = _T("c:\\windows\\system32\\");
		}
		else
		{
			strSysDir += _T("\\system32\\");
		}
		if (!PathFileExists(strSysDir + _T("AdbWinApi.dll")))
		{
			if (g_pPluginLogObject)
			{
				g_pPluginLogObject->Record(_T("ERROR:InitAdbApi-->PathFileExists failed"));
			}
			return FALSE;
		}
		m_hAdbwinapi = LoadLibrary(strSysDir + _T("AdbWinApi.dll"));
	}
	else
		m_hAdbwinapi = LoadLibrary(m_strAdbDllePath + _T("AdbWinApi.dll"));

	if (!m_hAdbwinapi)
	{
		if (g_pPluginLogObject)
		{
			g_pPluginLogObject->Record(_T("ERROR:InitAdbApi-->LoadLibrary failed"));
		}
		return FALSE;
	}
	m_pAdbCloseHandle = (AdbCloseHandle)GetProcAddress( m_hAdbwinapi, "AdbCloseHandle");
	if (m_pAdbCloseHandle==NULL)
	{
		if (g_pPluginLogObject)
		{
			g_pPluginLogObject->Record(_T("ERROR:InitAdbApi-->Get AdbCloseHandle failed"));
		}
		return FALSE;
	}

	m_pAdbEnumInterfaces = (AdbEnumInterfaces)GetProcAddress( m_hAdbwinapi, "AdbEnumInterfaces");
	if (m_pAdbEnumInterfaces==NULL)
	{
		if (g_pPluginLogObject)
		{
			g_pPluginLogObject->Record(_T("ERROR:InitAdbApi-->Get AdbEnumInterfaces failed"));
		}
		return FALSE;
	}

	m_pAdbNextInterface = (AdbNextInterface)GetProcAddress( m_hAdbwinapi, "AdbNextInterface");
	if (m_pAdbNextInterface==NULL)
	{
		if (g_pPluginLogObject)
		{
			g_pPluginLogObject->Record(_T("ERROR:InitAdbApi-->Get AdbNextInterface failed"));
		}
		return FALSE;
	}

	m_pAdbCreateInterface = (AdbCreateInterface)GetProcAddress( m_hAdbwinapi, "AdbCreateInterface");
	if (m_pAdbCreateInterface==NULL)
	{
		if (g_pPluginLogObject)
		{
			g_pPluginLogObject->Record(_T("ERROR:InitAdbApi-->Get AdbCreateInterface failed"));
		}
		return FALSE;
	}

	m_pAdbOpenDefaultBulkReadEndpoint = (AdbOpenDefaultBulkReadEndpoint)GetProcAddress( m_hAdbwinapi, "AdbOpenDefaultBulkReadEndpoint");
	if (m_pAdbOpenDefaultBulkReadEndpoint==NULL)
	{
		if (g_pPluginLogObject)
		{
			g_pPluginLogObject->Record(_T("ERROR:InitAdbApi-->Get AdbOpenDefaultBulkReadEndpoint failed"));
		}
		return FALSE;
	}
/*
	ADBAPIHANDLE adbHandle=NULL,pipeHandle=NULL;
	adbHandle = m_pAdbCreateInterface(usb_class_id,0x0bb4,0x0c02,0x1);
	if (adbHandle)
	{
		// 	 HANDLE hDevice = INVALID_HANDLE_VALUE;
		//  	 CString strDevPipe=_T("\\\\?\\usb#vid_0bb4&pid_0c02&mi_01#6&21ed2e15&0&0001#{f72fe0d4-cbcb-407d-8814-9ed673d0dd6b}\\BullkWrite");
		//  	 hDevice = CreateFile(strDevPipe,
		// 	 GENERIC_WRITE,
		//  	 FILE_SHARE_WRITE,
		// 	 NULL,
		//  	 OPEN_EXISTING,
		//  	 FILE_FLAG_OVERLAPPED,
		//  	 NULL);
		// 	 int iErr;
		// 	 iErr = GetLastError();
 		pipeHandle = m_pAdbOpenDefaultBulkReadEndpoint(adbHandle,AdbOpenAccessTypeReadWrite,AdbOpenSharingModeReadWrite);
 		m_pAdbCloseHandle(adbHandle);
 	}
	else
	{
		int iErr;
 		iErr = GetLastError();
	}
*/
	return TRUE;

}


VOID AdbOperator::DeInitAdbApi()
{
	if (m_hAdbwinapi)
	{
		FreeLibrary(m_hAdbwinapi);
		m_hAdbwinapi = NULL;
	}
	if (m_pAdbCloseHandle)
	{
		m_pAdbCloseHandle = NULL;
	}
	if (m_pAdbEnumInterfaces)
	{
		m_pAdbEnumInterfaces = NULL;
	}
	if (m_pAdbNextInterface)
	{
		m_pAdbNextInterface = NULL;
	}
}


int  AdbOperator::ScanAdbDevice()
{
	char entry_buffer[2048];
	char interf_name[2048];
	AdbInterfaceInfo* next_interface = (AdbInterfaceInfo*)(&entry_buffer[0]);
	unsigned long entry_buffer_size = sizeof(entry_buffer);
	char* copy_name;
	int nDeviceCount=0;
	// Enumerate all present and active interfaces.
	ADBAPIHANDLE enum_handle = m_pAdbEnumInterfaces(usb_class_id, true, true, true);

	if (NULL == enum_handle)
	{
		if (g_pPluginLogObject)
		{
			g_pPluginLogObject->Record(_T("ERROR:ScanAdbDevice-->AdbEnumInterfaces failed,ErrCode(%d)"),GetLastError());
		}
		return nDeviceCount;
	}

	while (m_pAdbNextInterface(enum_handle, next_interface, &entry_buffer_size))
	{
		// TODO: FIXME - temp hack converting wchar_t into char.
		// It would be better to change AdbNextInterface so it will return
		// interface name as single char string.
		const wchar_t* wchar_name = next_interface->device_name;
		for(copy_name = interf_name;L'\0' != *wchar_name;wchar_name++, copy_name++) 
		{
			*copy_name = (char)(*wchar_name);
		}
		*copy_name = '\0';

		nDeviceCount++;

		entry_buffer_size = sizeof(entry_buffer);
	}
	m_pAdbCloseHandle(enum_handle);
	return nDeviceCount;
}

int AdbOperator::Exec( char** bufRawOutput, const CString adbCmd, int nTimeoutCount )
{
    char cmd[MAX_PATH+256];
    CString strCmd = m_strModulePath + _T("bin\\adb.exe ") + adbCmd;
    em::EmCharSet::Tcs2Mbs(cmd, (LPTSTR)(LPCTSTR)strCmd);
	g_pPluginLogObject->Record(strCmd);
    return em::EmProcess::SendCommand(bufRawOutput, cmd, nTimeoutCount);
}

BOOL AdbOperator::IsAdbDeviceOnline()
{
    char *online = "device";
    char *retBuf = NULL;
    LPTSTR lpStr = NULL;
    int nSize = 0;
    int nRet = 0;
   
    nRet = Exec(&retBuf, _T("devices"), 5);
    if (nRet > 0) {
        char *ptr;
        ptr = strstr(retBuf, online);
        if (ptr) {
            if (retBuf)
            {
                delete retBuf;
                retBuf = NULL;
            }
            return TRUE;
        }
    }

    if (retBuf)
    {
        AnsiToUnicode(lpStr,nSize,retBuf);
        g_pPluginLogObject->Record(_T("IsAdbDeviceOnline faild, return:%d, reson:%s"), nRet, lpStr);
        delete retBuf;
		delete lpStr;
        retBuf = NULL;
    } 
    else
    {
        g_pPluginLogObject->Record(_T("IsAdbDeviceOnline faild, return:%d"), nRet);
    }

    return FALSE;
}

int AdbOperator::ExecPackCmd(long nUserdataSize)
{
    char *ok = "PACK_OK";
    char *error = "PACK_ERROR";
    char *retBuf = NULL;
    LPTSTR lpStr = NULL;
    int nSize = 0;
    int nRet = 0;
	int i=0;

	g_pPluginLogObject->Record(_T("ExecPackCmd nUserdataSize:%ld"), nUserdataSize);
    CString cmd;

    cmd.Format(_T("shell /system/bin/packdata.sh %u"), nUserdataSize);
	nRet = Exec(&retBuf, cmd, 60*5);
	
    if (nRet > 0) {
        char *ptr;
        ptr = strstr(retBuf, ok);
        if (ptr) {
            if (retBuf) {
                delete retBuf;
                retBuf = NULL;
            }
            return 0;
        } else {
            LPWSTR wstrRetBuf;
            int nSize;
            if (AnsiToUnicode(wstrRetBuf,nSize,retBuf)) {
                g_pPluginLogObject->Record(wstrRetBuf);
                delete wstrRetBuf;
                wstrRetBuf = NULL;
            }
            if (retBuf) {
                delete retBuf;
                retBuf = NULL;
            }
            return -1;
        }
        if (retBuf) {
            delete retBuf;
            retBuf = NULL;
        }
        return TRUE;
    }

    if (retBuf)
    {
        AnsiToUnicode(lpStr,nSize,retBuf);
        g_pPluginLogObject->Record(_T("ExecPackCmd faild, return:%d, reson:%s"), nRet, lpStr);
        delete retBuf;
		delete lpStr;
        retBuf = NULL;
    } 
    else
    {
        g_pPluginLogObject->Record(_T("ExecPackCmd faild, return:%d"), nRet);
    }
    return -2;
}

BOOL AdbOperator::PullImage(CString strTargetImagePath)
{
    char *tag = "KB/s";
    char *retBuf = NULL;
    LPTSTR lpStr = NULL;
    int nSize = 0;
    int nRet = 0;

    CString cmd = _T("pull /mnt/sdcard/databk.img ");
    cmd += strTargetImagePath;
    nRet = Exec(&retBuf, cmd, 600);
	//g_pPluginLogObject->Record(_T("PullImage %s\n"),retBuf);
    if (nRet > 0) {
        char *ptr;
        ptr = strstr(retBuf, tag);
        if (ptr) {
            if (retBuf) {
                delete retBuf;
                retBuf = NULL;
            }
            return TRUE;
        }
    }
    if (retBuf)
    {
        AnsiToUnicode(lpStr,nSize,retBuf);
        g_pPluginLogObject->Record(_T("PullImage faild, return:%d, reson:%s"), nRet, lpStr);
        delete retBuf;
		delete lpStr;
        retBuf = NULL;
    } 
    else
    {
        g_pPluginLogObject->Record(_T("PullImage faild, return:%d"), nRet);
    }
    return FALSE;
}

/////////////////////////////////////////////////////////////////////////////
// AdbOperator message handlers
Python kodu şu şekilde

Kod: Tümünü seç

import ctypes


class GUID(ctypes.Structure):
   _fields_ = [("Data1", ctypes.c_ulong),
               ("Data2", ctypes.c_ushort),
               ("Data3", ctypes.c_ushort),
               ("Data4", ctypes.c_ubyte*8)]


class AdbInterfaceInfo(ctypes.Structure):
   _fields_ = [("class_id", GUID),
               ("flags", ctypes.c_ulong),
               ("device_name", ctypes.c_wchar*800)]

def strGUID(GUID):
   string = ''
   string = string + '%x' % buff.class_id.Data1 + '-%x' % buff.class_id.Data2 + '-%x' % buff.class_id.Data3
   string = string + '-%x' % buff.class_id.Data4[0]
   string = string + '%x' % buff.class_id.Data4[1]
   string = string + '%x' % buff.class_id.Data4[2]
   string = string + '%x' % buff.class_id.Data4[3]
   string = string + '%x' % buff.class_id.Data4[4]
   string = string + '%x' % buff.class_id.Data4[5]
   string = string + '%x' % buff.class_id.Data4[6]
   string = string + '%x' % buff.class_id.Data4[7]
   return string

dll = ctypes.cdll.LoadLibrary('AdbWinApi.dll')
usb_class_id = GUID(0xF72FE0D4, 0xCBCB, 0x407d, (0x88, 0x14, 0x9e, 0xd6, 0x73, 0xd0, 0xdd, 0x6b))
enum_handle = dll.AdbEnumInterfaces(usb_class_id, ctypes.c_bool('true'), ctypes.c_bool('true'), ctypes.c_bool('true'))

while(1):
   buff = AdbInterfaceInfo()
   size = ctypes.c_ulong(ctypes.sizeof(buff))
   status = dll.AdbNextInterface(enum_handle, ctypes.byref(buff), ctypes.byref(size))

   if status==1:
       #print "GUID = " + strGUID(buff.class_id)
       #print "status = " + str(status)
       #print "Name = " + str(buff.device_name)
       hAdbApi = dll.AdbCreateInterfaceByName(buff.device_name);
       if hAdbApi == 0:
           print 'AdbCreateInterfaceByName Fail'
       else:
           serial = ' '*128
           pserial = ctypes.c_char_p()
           pserial.value = serial
           serial_len = ctypes.c_ulong(len(serial))
           ret = dll.AdbGetSerialNumber(hAdbApi, pserial, ctypes.byref(serial_len), ctypes.c_bool('false'));
           if ret == 1:
               print 'Device Name: ' + '%s'% serial
           else:
               print 'Get Device Name Fail'
   else:
       print 'Finished'
       break




Benim kodumda şu şekilde.

Kod: Tümünü seç

unit Unit1;

interface

uses
 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
 TForm1 = class(TForm)
   mmo1: TMemo;
   btn1: TButton;
   procedure btn1Click(Sender: TObject);
   procedure FormCreate(Sender: TObject);
   procedure FormDestroy(Sender: TObject);

 private
   { Private declarations }
 public
   { Public declarations }
 end;
type

 ADBAPIHANDLE = Pointer;
type
AdbInterfaceInfo = packed record
   class_id: TGUID;
   flags : LongWord;
   device_name: Pwidechar;
 end;

var
 Form1: TForm1;
 AdbLoad: THandle;
 enum_handle: ADBAPIHANDLE;

 AdbEnumInterfaces:  function(class_id: TGUID; exclude_not_present: Boolean;
                                                exclude_removed:     Boolean;
                                                active_only:         Boolean): ADBAPIHANDLE; cdecl;

 AdbNextInterface:  function(adb_handle:ADBAPIHANDLE;Info : AdbInterfaceInfo;Size : LongWord): Bool; cdecl;
implementation

{$R *.dfm}


Procedure LoadMyLibrary(FileName: String);
begin
   AdbLoad := LoadLibrary(PWideChar(FileName));
     if AdbLoad = 0 then begin
         MessageBox(0,'Hata',0,0);
         exit;
     end;
   AdbEnumInterfaces := GetProcAddress(Adbload, 'AdbEnumInterfaces');
   AdbNextInterface  := GetProcAddress(AdbLoad, 'AdbNextInterface');
   //AdbCloseHandle    := GetProcAddress(AdbLoad, 'AdbCloseHandle');
     if @AdbEnumInterfaces = nil then
     begin
        MessageBox(0,'Hata',0,0);
        exit;
     end;

          if @AdbNextInterface = nil then
          begin
        MessageBox(0,'Hata',0,0);
        exit;
     end;



end;




procedure TForm1.btn1Click(Sender: TObject);

const
   ANDROID_USB_CLASS_ID: TGUID = '{F72FE0D4-CBCB-407d-8814-9ED673D0DD6B}';
   var
   Checkinfo : AdbInterfaceInfo;
   Size : LongWord;
begin
enum_handle := AdbEnumInterfaces(ANDROID_USB_CLASS_ID, True, True, True);





 if AdbNextInterface(enum_handle,Checkinfo,Size) then
  ShowMessage('başarılı')
  else
  ShowMessage('hata');




end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 LoadMyLibrary('AdbWinApi.dll');
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeLibrary(Adbload);
end;

end.

AdbInterfaceInfo bulunan device_name pwide char yerine array char olarak kullandım gene hata ile karşılaşıyorum.Altta kullandığım dll dosyaları var. Yardımcı olabilirmisiniz nerede hata yapıyorum ?

Kullandığım dll dosyaları

https://drive.google.com/file/d/1Tx-gDA ... vttlL/view

Cevapla