|
În primul rând, creează un proiect DLL C++
Modificați CPPTest.cpp astfel încât să spună: CPPTest.cpp : Definește punctul de intrare pentru aplicația DLL.
// #include "stdafx.h" #include #ifdef _MANAGED #pragma reușit (împingere, oprire) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved
)
{ returnează TRUE;
} extern "C"
{ struct TestStruct
{ int i; car* str; }; _declspec(dllexport) size_t __stdcall GetStringLength(char* & str)
{ strlen(strlen) de revenire;
} _declspec(dllexport) int __stdcall AddTwoNumber(const int a,const int b)
{ returnează a+b;
} _declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{ folosind spațiul de nume STD; cout<<s.i<<endl; cout<<s.str<<endl; s.i=54321; s.str="Sunt toți morți!";
}
} #ifdef _MANAGED #pragma gestionat (pop) #endif
2. Creează un proiect de test C#
Modifică conținutul Programului pentru: folosind Sistem; folosind System.Collections.Generic; folosind System.Text; folosind System.Runtime.InteropServices; spațiu de nume ConsoleApplicationTestCSharp
{ Programul clasei
{ [DllImport("CPPTest.dll")] extern static int GetStringLength(ref string str); [DllImport("CPPTest.dll")] static extern int AddTwoNumber(int a, int b); [DllImport("CPPTest.dll")] static extern void StructTest (ref TestStruct s); static void Main(string[] args)
{ string testString = "HAHA! Sunt un șir de test"; 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 = "Mergi să tragi răul pe munte!"; StructTest(ref s); Console.WriteLine(s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] struct public TestStruct
{ public int i; public string str;
}
}
} Observați eticheta DllImportAttribute de mai susmetodă。 Rezultatul run-ului: lungime(C++)=24 lungime(C#)=24 a+b(C++)=1010 a+b(C#)=1010
12345 Du-te să tragi răul pe munți!
54321 Sunt toți morți! În al treilea rând, o explicație a mai multor cuvinte-cheie în C/C++ _declspec __stdcall extern
"C" (dllexport) exportă din DLL folosind __declspec (dllexport). </s.str<<endl; </s.i<<endl;
|