Jump to content

How generate a error code from C# dll to macro @error in AutoIt?


Luigi
 Share

Recommended Posts

Greetings, someone can give a exemple, how send a error from a C#'s dll to AutoIt?

I use this line, to send an error... but, I want get a error code In AutoIt with macro @error, it's possible?

 

throw new ArgumentException("arquivo map não existe", "value" );

In this way, work, I know ther are error, but, @errror always is zero.

I don't want this, I want a number as error code.

Can you help me?

 

Best regards

Visit my repository

Link to comment
Share on other sites

@Jos, thank you for reply, this is the code:

Obs: this is not game automation, this is my game writed in AutoIt.

https://www.youtube.com/watch?v=dq8UWEDU7q8

I want re-write some code in C#/dll.

AutoIt:

Global Const $sNameSpace = "Borius"
Global Const $sClass = "Engine"
Global Const $BORIUS_DLL = """" & @ScriptDir & "\borius.dll"""
ConsoleWrite($BORIUS_DLL & @LF)
Global Const $REGASM = "C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe"
;~ RunWait($REGASM & " /unregister " & $BORIUS_DLL, @ScriptDir, @SW_HIDE)

;~ Global $PID = RunWait($REGASM & " /register /codebase /tlb " & $BORIUS_DLL, @ScriptDir, @SW_HIDE)
;~ Global $PID = RunWait($REGASM & "  /codebase " & $BORIUS_DLL, @ScriptDir, @SW_HIDE)
Global $PID = Run(@ComSpec & " /c " & $REGASM & " /register /codebase /tlb " & $BORIUS_DLL, @ScriptDir,  @SW_HIDE, $STDIN_CHILD + $STDOUT_CHILD + $STDERR_CHILD + $STDERR_MERGED)

ProcessWaitClose($PID)
Local $sOutput = StdoutRead($PID)
ConsoleWrite($sOutput & @LF)

Global $wer = ObjCreate($sNameSpace & "." & $sClass)
If @error Or Not IsObj($wer) Then
    Local $sOutput = StdoutRead($PID)
    ConsoleWrite($sOutput & @LF)
    ConsoleWrite($sNameSpace & "." & $sClass & " @error[" & @error & "]" & @LF)
    Exit
Else
    ConsoleWrite($sNameSpace & "." & $sClass & " @ok" & @LF)
EndIf

The dll:

/*
 * Criado por SharpDevelop.
 * Usuário: master
 * Data: 14/09/2017
 * Hora: 18:21
 * 
 * Para alterar este modelo use Ferramentas | Opções | Codificação | Editar Cabeçalhos Padrão.
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;

namespace borius{
    /// <summary>
    /// Description of MyClass.
    /// </summary>
    public class Engine{
    private string _map;
    
    private int height;
    //private int layers;
    private int nextobjectid;
    private string orientation;
    //private int properties;
    //private int propertytypes;
    private int renderorder;
    private int tiledversion;
    private int tileheight;
    //private int tilesets;
    private int tilewidth;
    private string type;
    private int version;
    private int width;
        
        dynamic json;
        
        
        
        public string map{
            get{ return _map; }
            set{
                value = value.Replace("\\", "\\\\");
                if( !File.Exists(value) ){
                    throw new ArgumentException("arquivo map não existe", "value" );
                }
                JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            
                using (StreamReader r = new StreamReader(value)) {
                    string str = r.ReadToEnd();
                    json = serializer.DeserializeObject(str);
                }
                _map_build();
                _map = value;
            }
        }
        

        public void _map_build(){
            foreach (KeyValuePair<string, object> entry in json){
                var key = entry.Key;
                switch( key ){
                    case "height" :
                        height = Int32.Parse(entry.Value as string);
                        break;
                    case "layers" :
                    case "nextobjectid" :
                        nextobjectid = Int32.Parse(entry.Value as string);
                        break;
                    case "orientation" : 
                    case "properties" : 
                    case "propertytypes" : 
                    case "renderorder" : 
                    case "tiledversion" :
                    case "tileheight" :
                        tileheight = Int32.Parse(entry.Value as string);
                        break;
                    case "tilesets" : 
                    case "tilewidth" : 
                        tilewidth = Int32.Parse(entry.Value as string);
                        break;
                    case "type" :
                    case "version" :
                        version = Int32.Parse(entry.Value as string);
                        break;
                    case "width" :
                        width = Int32.Parse(entry.Value as string);
                        break;

                }
                
                
                var value = entry.Value as string;
                Console.WriteLine(String.Format("{0} : {1}",key, value));
            }
            
        }
        
    }
}

 

Visit my repository

Link to comment
Share on other sites

Instead of a void dll function, make it return an int to AutoIt containing a status code, e.g., 0=success, 1-n = various error codes. Capture this in your dllcall from autoit ($return=DllCall(...), $myErrorCode=$return[0]), and use SetError to fill the @error macro). Letting your dll write to console and AutoIt capturing that seems needlessly circuitous (and potentially error-prone), since dllcalls are designed to return information to the caller.

Link to comment
Share on other sites

Thank you for your reply @RTFC, but I thinking dll writed in C++, you work like you say.

I my opinion, dll writed in C#, work throug COM (componente object model), see this:

http://forum.autoitbrasil.com/index.php?/topic/1869-criando-uma-dll-em-c-csharp/

Any "throw new xxxxxx" break the script, and not set AutoIt's @error.

Your way is smart, but I still unknow hos set @error code.

If I wrong, apologize-me, it's new for me.

Edited by Luigi

Visit my repository

Link to comment
Share on other sites

Luigi, You are right. C# code is managed .NET code and a C# DLL-file is a .NET assembly DLL-file and can as such not be used by DllCall. DllCall can be used to call functions implemented in unmanaged code in conventional DLL-files like the DLL-files in the Windows operating system that implements Windows API functions.

C# is an object oriented language and everything is done through objects, properties and methods. To call a method in a C# DLL-file you create an object and executes the object method.

A general and easy way to set the @error macro when an error occurs in C# code is demonstrated in this pseudocode (cannot be run):

// Use a global variable and a separate
// function to pass an error code to AutoIt.

using System;
class Au3Class {
  int iErrorCode = 0;

  public int GetErrorCode() {
    return iErrorCode;
  }

  public void Method1() {
    iErrorCode = 0; // Initialize iErrorCode
    Console.WriteLine( "Method1 without errors" );
  }

  public void Method2() {
    iErrorCode = 0; // Initialize iErrorCode
    Console.WriteLine( "Method2 with an error" );
    iErrorCode = 1; // Set iErrorCode on error
  }
}
Example()
If @error Then
  ConsoleWrite( "@error = " & @error & @CRLF )
  Exit ; Exit on error
EndIf

Func Example()
  Local $iError

  $oAu3Class.Method1() ; Call the actual method
  $iError = $oAu3Class.GetErrorCode() ; Check error code
  If $iError Then Return SetError( $iError, 0, -1 )
  ; No errors, continue Example()
  ConsoleWrite( "No Errors" & @CRLF & @CRLF )

  $oAu3Class.Method2() ; Call the actual method
  $iError = $oAu3Class.GetErrorCode() ; Check error code
  If $iError Then Return SetError( $iError, 0, -1 )
  ; No errors, continue Example()
  ConsoleWrite( "No Errors" & @CRLF & @CRLF )
EndFunc

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...