Como ler string de ponteiro para buffer em c#
-
21-09-2019 - |
Pergunta
Como posso ler a string de erro em C# desta chamada C ++ DLL?
//
// 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);
obrigado!
Solução
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 );
Outras dicas
Se você alterar o tipo de dados de byte* para intptr, isso pode funcionar:
Ou um dos string
construtores (um deles também inclui um Encoding
parâmetro):
Marshal.alochglobal (int) mais Marshal.ptrtostringauto (intptr, int) talvez?
Algum contexto de código seria bom, pois estou assumindo que você já está coagindo byte*
em um IntPtr
Usando P/Invoke ou algum outro truque.
Basicamente, chame sua função para obter o tamanho do buffer, aloque um buffer usando AllocHGlobal()
, chame novamente, leia a string e depois liberte o buffer (usando Marshall.FreeHGlobal(IntPtr)
). Isso supõe que você possa usar o alocador de Marshall, é claro.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow