Domanda

Ho una struttura in C ++

struct UnmanagedStruct
{
   char* s;
   // Other members
};

e una struttura C #

struct ManagedStruct {
   [MarshalAs(UnmanagedType.LPStr)]
   string s;
   // Other members
}

espone la libreria C ++

extern "C" UnmanagedStruct __declspec(dllexport) foo( char* input );

Ed è importato come

  [DllImport("SomeDLL.dll", CharSet = CharSet.Ansi)]
  static extern ManagedStruct foo( string input );

Tuttavia quando chiamo questa funzione ottengo

MarshalDirectiveException non è stato gestito

La firma del tipo di metodo non è compatibile con PInvoke.

Il fatto è che questa chiamata di funzione funziona se rimuovo i caratteri * e le stringhe dalle strutture.

È stato utile?

Soluzione

Per questo tipo di scenario, non utilizzare direttamente una stringa. Invece cambia il tipo in un valore IntPtr e usa Marshal.PtrToStringAuto / Ansi / Uni come appropriato. In questo caso, poiché il tuo codice nativo utilizza char * , PtrToStringAnsi è la scelta migliore.

struct ManagedStruct {
  IntPtr s;
  public string sAsString { get { return Marshal.PtrToStringAnsi(s); } }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top