|
Najprv vytvorte DLL projekt v C++
Upravte CPPTest.cpp, aby ste čítali: CPPTest.cpp : Definuje vstupný bod pre DLL aplikáciu.
// #include "stdafx.h" #include #ifdef _MANAGED #pragma zvládnuté (odtlačiť, odtlačiť) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved
)
{ return TRUE;
} externé "C"
{ struct TestStruct
{ int i; char* str; }; _declspec(dllexport) size_t __stdcall GetStringLength(char* & str)
{ return strlen(str);
} _declspec(dllexport) int __stdcall AddTwoNumber(const int a,const int b)
{ vrátiť a+b;
} _declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{ pomocou menného priestoru std; cout<<s.i<<endl; cout<<s.str<<endl; s.i=54321; s.str="Všetci sú mŕtvi!";
}
} #ifdef _MANAGED #pragma zvládnuté (pop) #endif
2. Vytvoriť testovací projekt v C#
Upraviť obsah programu na: pomocou systému; používajúc System.Collections.Generic; pomocou System.Text; používajúc System.Runtime.InteropServices; menný priestor ConsoleApplicationTestCSharp
{ Triedny program
{ [DllImport("CPPTest.dll")] static extern int GetStringLength(ref string str); [DllImport("CPPTest.dll")] statický extern intAddTwoNumber (int a, int b); [DllImport("CPPTest.dll")] statický externý void StructTest (ref TestStruct s); static void Main (string[] args)
{ string testString = "HAHA! Som skúšobná niť"; 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 = nový TestStruct(); s.i = 12345; s.str = "Choď strieľať zlo na horách!"; StructTest(ref s); Console.WriteLine(s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] verejná štruktúra TestStruct
{ verejné int i; verejná struna str;
}
}
} Všimnite si vyššie označenie DllImportAttributemetóda。 Výsledok behu: dĺžka(C++)=24 dĺžka(C#)=24 a+b(C++)=1010 a+b(C#)=1010
12345 Choď strieľať zlo na horách!
54321 Všetci sú mŕtvi! Po tretie, vysvetlenie viacerých kľúčových slov v C/C++ _declspec __stdcall externý
"C" (dllexport) exportuje z DLL pomocou __declspec (dllexport). </s.str<<endl; </s.i<<endl;
|