|
Nejprve vytvořte DLL projekt v C++
Upravte CPPTest.cpp tak, aby bylo zněno: CPPTest.cpp : Definuje vstupní bod pro aplikaci DLL.
// #include "stdafx.h" #include #ifdef _MANAGED #pragma zvládnut (odraz, dolů) #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átit a+b;
} _declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{ pomocí jmenného prostoru std; Cout<<s.i<<endl; cout<<s.str<<endl; s.i=54321; s.str="Všichni jsou mrtví!";
}
} #ifdef _MANAGED #pragma řízeno (pop) #endif
2. Vytvořit testovací projekt v C#
Upravte obsah programu tak, aby: pomocí System; pomocí System.Collections.Generic; pomocí System.Text; pomocí System.Runtime.InteropServices; jmenný prostor ConsoleApplicationTestCSharp
{ Program tříd
{ [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! Jsem testovací struna"; 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 = "Jděte střílet zlo na horách!"; StructTest(ref s); Console.WriteLine(s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] veřejná struktura TestStruct
{ veřejné int i; veřejná struna str;
}
}
} Všimněte si výše uvedeného štítku DllImportAttributemetoda。 Výsledek běhu: délka(C++)=24 délka(C#)=24 a+b(C++)=1010 a+b(C#)=1010
12345 Jděte střílet zlo na horách!
54321 Všichni jsou mrtví! Za třetí, vysvětlení několika klíčových slov v C/C++ _declspec __stdcall externí
"C" (dllexport) exportuje z DLL pomocí __declspec (dllexport). </s.str<<endl; </s.i<<endl;
|