2012-04-22 11 views
9

Ho 2 funzioni all'interno di una classe e ricevo un errore nella chiamata per la funzione ParseBits(), ad esempio "int num_elements = ParseBits(bits, buffer);" a causa del "buffer" argomento che sto passando "public int ParseBits(string bits, int* buffer) ":I puntatori e i buffer di dimensioni fisse possono essere utilizzati solo in un contesto non sicuro

Funzione 1:

public float AssignFitness(string bits, int target_value) 
     { 

    //holds decimal values of gene sequence 
    int[] buffer = new int[(VM_Placement.AlgorithmParameters.chromo_length/VM_Placement.AlgorithmParameters.gene_length)]; 

    int num_elements = ParseBits(bits, buffer); 

    // ok, we have a buffer filled with valid values of: operator - number - operator - number.. 
    // now we calculate what this represents. 
    float result = 0.0f; 

    for (int i=0; i < num_elements-1; i+=2) 
    { 
     switch (buffer[i]) 
     { 
     case 10: 

      result += buffer[i+1]; 
      break; 

     case 11: 

      result -= buffer[i+1]; 
      break; 

     case 12: 

      result *= buffer[i+1]; 
      break; 

     case 13: 

      result /= buffer[i+1]; 
      break; 

     }//end switch 

    } 

    // Now we calculate the fitness. First check to see if a solution has been found 
    // and assign an arbitarily high fitness score if this is so. 

    if (result == (float)target_value) 

     return 999.0f; 

    else 

     return 1/(float)fabs((double)(target_value - result)); 
    // return result; 
} 

Funzione 2:

public int ParseBits(string bits, int* buffer) 
     { 

      //counter for buffer position 
      int cBuff = 0; 

      // step through bits a gene at a time until end and store decimal values 
      // of valid operators and numbers. Don't forget we are looking for operator - 
      // number - operator - number and so on... We ignore the unused genes 1111 
      // and 1110 

      //flag to determine if we are looking for an operator or a number 
      bool bOperator = true; 

      //storage for decimal value of currently tested gene 
      int this_gene = 0; 

      for (int i = 0; i < VM_Placement.AlgorithmParameters.chromo_length; i += VM_Placement.AlgorithmParameters.gene_length) 
      { 
       //convert the current gene to decimal 
       this_gene = BinToDec(bits.Substring(i, VM_Placement.AlgorithmParameters.gene_length)); 

       //find a gene which represents an operator 
       if (bOperator) 
       { 
        if ((this_gene < 10) || (this_gene > 13)) 

         continue; 

        else 
        { 
         bOperator = false; 
         buffer[cBuff++] = this_gene; 
         continue; 
        } 
       } 

       //find a gene which represents a number 
       else 
       { 
        if (this_gene > 9) 

         continue; 

        else 
        { 
         bOperator = true; 
         buffer[cBuff++] = this_gene; 
         continue; 
        } 
       } 

      }//next gene 

      // now we have to run through buffer to see if a possible divide by zero 
      // is included and delete it. (ie a '/' followed by a '0'). We take an easy 
      // way out here and just change the '/' to a '+'. This will not effect the 
      // evolution of the solution 
      for (int i = 0; i < cBuff; i++) 
      { 
       if ((buffer[i] == 13) && (buffer[i + 1] == 0)) 

        buffer[i] = 10; 
      } 

      return cBuff; 
     } 

sto ottenendo 2 errori per queste funzioni sulla riga evidenziata s:

Error 1: The best overloaded method match for 'VM_Placement.Program.ParseBits(string, int*)' has some invalid arguments 

Error 2: Pointers and fixed size buffers may only be used in an unsafe context 
+0

Allora, qual è la tua domanda? perché ottieni gli errori? cosa puoi fare per evitarli? perché non è possibile utilizzare i puntatori nel codice gestito o qualcosa di diverso? (sapere esattamente che cosa ti aiuta a facilitare l'aiuto che se dovessimo indovinare, potremmo avere ragione e potremmo non farlo) –

+0

Cosa posso fare per evitarli ... Suppongo che sto passando gli argomenti in ParseBits() funziona in modo errato e quindi ricevo un altro errore "Argomento 2: impossibile convertire da 'int []' a 'int *'" – user1277070

+0

Perché stai usando i puntatori in primo luogo? – harold

risposta

5

Forse ho perso, ma non sembrano essere facendo tutto ciò che richiede in realtà l'uso di un int*. Perché non semplicemente passare un array int e cambiare la firma funzione ParseBits a:

public int ParseBits(string bits, int[] buffer)

e rimuovere i blocchi unsafe{ ... } tutto.

19

È necessario racchiudere la funzione utilizzando i puntatori prime in un blocco unsafe.

unsafe 
{ 
//your code 
} 
+0

e come chiamare quella funzione allora? rendendo la funzione non sicura rimossa l'errore "Puntatori e buffer di dimensioni fisse possono essere utilizzati solo in un contesto non sicuro", ma sto ancora ottenendo "La migliore corrispondenza del metodo sovraccarico per" VM_Placement.Program.ParseBits (string, int *) "ha alcuni argomenti non validi "su quella chiamata di funzione. – user1277070

+0

Direi che anche renderebbe il sito di chiamata della tua funzione "non sicuro" poiché richiede anche dei puntatori. –

+0

Nopes non ha funzionato ... credo sia a causa del tipo di discussioni che sto passando ...Ricevo un errore in più per l'argomento passare durante la chiamata a ParseBits() "Argomento 2: impossibile convertire da 'int []' a 'int *'" – user1277070

1

Ho avuto lo stesso problema, ma non è stato risolto da nessuna delle altre risposte qui sopra. Ho continuato a ricevere errori diversi.

Qualsiasi funzione utilizzi codice non sicuro deve semplicemente essere dichiarata con la parola chiave "non sicura".
Per esempio:

static unsafe void myFunction(int* myInt, float* myFloat) 
{ 
    // Function definition 
} 

Personalmente, stavo cercando di fare questo quando si effettua una classe wrapper.
Per chi fosse interessato, è finito per guardare qualcosa di simile:

using System.Runtime.InteropServices; 

namespace myNamespace 
{ 
    public class myClass 
    { 
     [DllImport("myLib.so", EntryPoint = "myFunction")] 
     public static extern unsafe void myFunction(float* var1, float* var2); 
    } 
} 

C'è un sacco di informazioni in MSDN "Unsafe Codice Tutorial":
https://msdn.microsoft.com/en-us/library/aa288474(v=vs.71).aspx

E 'probabilmente la pena di leggere, mi trovato abbastanza utile.

Problemi correlati