Compartilhar via


Como: Chamar DLLs nativas a partir do código gerenciado usando PInvoke

Functions that are implemented in unmanaged DLLs can be called from managed code using Platform Invoke (P/Invoke) functionality. If the source code for the DLL is not available, P/Invoke is the only option for interoperating. No entanto, diferentemente de outros.NET idiomas, o Visual C++ fornece uma alternativa para P/Invoke. For more information, see Usar a interoperabilidade de C++ (PInvoke implícito).

Exemplo

O exemplo de código a seguir usa o Win32 GetSystemMetrics função para recuperar a resolução atual da tela em pixels.

For functions that use only intrinsic types as arguments and return values, no extra work is required. Outros tipos de dados, como, por exemplo, ponteiros de função, matrizes e estruturas, exigem atributos adicionais para garantir o empacotamento de dados apropriados.

Although it is not required, it is good practice to make P/Invoke declarations static members of a value class so that they do not exist in the global namespace, as demonstrated in this example.

// pinvoke_basic.cpp
// compile with: /clr
using namespace System;
using namespace System::Runtime::InteropServices;

value class Win32 {
public:
   [DllImport("User32.dll")]
   static int GetSystemMetrics(int);

   enum class SystemMetricIndex {
      // Same values as those defined in winuser.h.
      SM_CXSCREEN = 0,
      SM_CYSCREEN = 1
   };
};

int main() {
   int hRes = Win32::GetSystemMetrics( safe_cast<int>(Win32::SystemMetricIndex::SM_CXSCREEN) );
   int vRes = Win32::GetSystemMetrics( safe_cast<int>(Win32::SystemMetricIndex::SM_CYSCREEN) );
   Console::WriteLine("screen resolution: {0},{1}", hRes, vRes);
}

Consulte também

Outros recursos

Usando PInvoke explícita em C++ (atributo DllImport)