|
Per prima cosa, crea un progetto DLL in C++
Modifica CPPTest.cpp per leggere: CPPTest.cpp : Definisce il punto di ingresso per l'applicazione DLL.
// #include "stdafx.h" #include #ifdef _MANAGED #pragma gestito (spinta, fuori) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved
)
{ ritorna VERO;
} esterno "C"
{ struct TestStruct
{ int i; car* str; }; _declspec(dllexport) size_t __stdcall GetStringLength(char* & str)
{ a rientrare strlen(strlen);
} _declspec(dllexport) int __stdcall AddTwoNumber(const int a,const int b)
{ restituisci A+B;
} _declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{ usando lo standard standard dello spazio dei nomi; cout<<s.i<<endl; cout<<s.str<<endl; s.i=54321; s.str="Sono tutti morti!";
}
} #ifdef _MANAGED #pragma gestito (pop) #endif
2. Creare un progetto di test in C#
Modifica il contenuto del programma per: usando Sistema; usando System.Collections.Generic; usando System.Text; usando System.Runtime.InteropServices; namespace ConsoleApplicationTestCSharp
{ Programma di classe
{ [DllImport("CPPTest.dll")] static extern int GetStringLength(ref stringstringa str); [DllImport("CPPTest.dll")] static extern int AddTwoNumber(int a, int b); [DllImport("CPPTest.dll")] vuoto esterno statico StructTest (rif. TestStruct s); vuoto statico Main(string[] args)
{ string testString = "HAHA! Sono una stringa di prova"; Console.WriteLine("length(C++)=" + GetStringLength(ref testString). ToString()); Console.WriteLine("length(C#)=" + testString.Length.ToString()); Console.WriteLine("a+b(C++)=" + AddTwoNumber(10, 1000)); Console.WriteLine("a+b(C#)=" + (10 + 1000)); TestStruct s = new TestStruct(); s.i = 12345; s.str = "Vai a sparare ai malvagi sulle montagne!"; StructTest (rif); Console.WriteLine(s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] struct pubblico TestStruct
{ public int i; str di corde pubbliche;
}
}
} Nota il tag DllImportAttribute soprametodo。 Risultato della partita: length(C++)=24 length(C#)=24 a+b(C++)=1010 a+b(C#)=1010
12345 Vai a sparare ai malvagi sulle montagne!
54321 Sono tutti morti! Terzo, una spiegazione di diverse parole chiave in C/C++ _declspec __stdcall Extern
"C" (dllexport) esporta dalla DLL usando __declspec (dllexport). </s.str<<endl; </s.i<<endl;
|