|
Először hozzon létre egy C++ DLL projektet
Módosítsd CPPTest.cpp a következő fellépésre: CPPTest.cpp : Meghatározza a DLL alkalmazás belépési pontját.
// #include "stdafx.h" #include #ifdef _MANAGED #pragma sikerült (tolni, lelementeni) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved
)
{ return TRUE;
} külső "C"
{ struct TestStruct
{ int i; char* str; }; _declspec(dllexport) size_t __stdcall GetStringLength(char* & str)
{ return strlen (strlen);
} _declspec(dllexport) int __stdcall AddTwoNumber(const int a,const int b)
{ return a+b;
} _declspec(dllexport) void __stdcall StructTest(TestStruct&s)
{ névtér std használatával; cout<<s.i<<endl; cout<<s.str<<endl; s.i=54321; s.str="Mind meghaltak!";
}
} #ifdef _MANAGED #pragma menedzsel(pop) #endif
2. Hozz létre egy C# tesztprojektet
Módosítsd a program tartalmát a következőképpen a következőképpen módosítsák: System használatával; System.Collections.Generic használatával; System.Text használatával; System.Runtime.InteropServices használatával; névtér ConsoleApplicationTestCSharp
{ Osztályprogram
{ [DllImport("CPPTest.dll")] statikus külső int GetStringLength (ref string str); [DllImport("CPPTest.dll")] statikus külső int AddTwoNumber(int a, int b); [DllImport("CPPTest.dll")] static extern void StructTest(ref TestStruct s); statikus void Main(string[] args)
{ string testString = "HAHA! Én vagyok egy teszthúr"; 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 = új TestStruct(); s.i = 12345; s.str = "Menj és lőj gonoszságot a hegyekre!"; StructTest(ref s); Console.WriteLine(s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] public struct TestStruct
{ nyilvános int I; nyilvános húros erő;
}
}
} Figyeld meg a fenti DllImportAttribute címkétmódszer。 Futás eredménye: length(C++)=24 length(C#)=24 a+b(C++)=1010 a+b(C#)=1010
12345 Menj, hogy a hegyekre lőj gonoszokat!
54321 Mind halottak! Harmadszor, több kulcsszó magyarázata C/C++ nyelven _declspec __stdcall Külső
"C" (dllexport) exportálja a DLL-ről __declspec (dllexport) segítségével. </s.str<<endl; </s.i<<endl;
|