Domanda

Come posso leggere la stringa di errore in C# da questa chiamata DLL C ++?

//
//  PARAMETERS:
//      objptr
//          Pointer to class instance.
//
//      pBuffer
//          Pointer to buffer receiving NULL terminated error message string.   
//          If this value is zero, the function returns the required buffer size, in bytes,
//          and makes no use of the pBuffer. 
//
//      nSize
//          Size of receiving buffer.
//          If this value is zero, the function returns the required buffer size, in bytes,
//          and makes no use of the pBuffer. 
//
//  RETURN VALUES:
//      If pBuffer or nSize is zero, the function returns the required buffer size, in bytes.
//      If the function succeeds, the return value is number of bytes copied into pBuffer.
//      If function fails return value is 0.
//
extern unsafe int GetError(uint objptr, byte* pBuffer, int nSize);

Grazie!

È stato utile?

Soluzione

byte[] buffer = new byte[1000];
int size;
unsafe
{
  fixed ( byte* p = buffer )
  {
    size = GetError( ???, p, buffer.Length ); 
  }
}
string result = System.Text.Encoding.Default.GetString( buffer, 0, size );

Altri suggerimenti

Se si modifica il tipo di dati da byte* a intptr, questo potrebbe funzionare:

Marshal.Ptrtostringansi

O uno dei string costruttori (uno di loro include anche un Encoding parametro):

Costruttori di stringhe

Marshal.allochglobal (int) più Marshal.PtrtostringAuto (intptr, int) forse?

Un contesto di codice sarebbe bello, poiché presumo che tu stia già costringendo byte* in un IntPtr Usando P/invoca o qualche altro inganno.

Fondamentalmente, chiama la tua funzione per ottenere la dimensione del buffer, alloca un buffer utilizzando AllocHGlobal(), chiamalo di nuovo, leggi la stringa, quindi libera il buffer (usando Marshall.FreeHGlobal(IntPtr)). Questo presuppone che tu possa usare l'allocatore di Marshall, ovviamente.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top