|
Vispirms izveidojiet C++ DLL projektu
Mainīt CPPTest.cpp šādi: CPPTest.cpp : Definē DLL lietojumprogrammas ieejas punktu.
// #include "stdafx.h" #include #ifdef _MANAGED #pragma pārvaldīts (push, off) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved
)
{ atgriezt TRUE;
} ārējais "C"
{ struct TestStruct
{ int i; char* str; }; _declspec(dllexport) size_t __stdcall GetStringLength(char* & str)
{ atgriezt strlen(str);
} _declspec(dllexport) int __stdcall AddTwoNumber(const int a,const int b)
{ atgriezt a+b;
} _declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{ izmantojot nosaukumvietas std; cout<<s.i<<endl; cout<<s.str<<endl; s.i=54321; s.str="Viņi visi ir miruši!";
}
} #ifdef _MANAGED #pragma pārvaldīts(pop) #endif
2. Izveidojiet C# testa projektu
Modificēt programmas saturu, lai: izmantojot Sistēmu; izmantojot System.Collections.Generic; izmantojot System.Text; izmantojot System.Runtime.InteropServices; nosaukumvieta ConsoleApplicationTestCSharp
{ nodarbību programma
{ [DllImport("CPPTest.dll")] static extern int GetStringLength(ref string str); [DllImport("CPPTest.dll")] statiskais ārējais int AddTwoNumber(int a, int b); [DllImport("CPPTest.dll")] statisks ārējais tukšums StructTest(ref TestStruct s); statisks tukšums Main(virkne[] argumenti)
{ string testString = "HAHA! Es esmu testa virkne"; 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 = jauns TestStruct(); s.i = 12345; s.str = "Ej šaut ļaunumu uz kalniem!"; StructTest(ref s); Console.WriteLine (s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] publiskā struktūra TestStruct
{ publiskais int i; publiskā stīgu str;
}
}
} Ņemiet vērā iepriekš minēto tagu DllImportAttributemetode。 Izpildes rezultāts: garums (C++)=24 garums (C#)=24 a+b(C++)=1010 a+b(C#)=1010
12345 Dodieties šaut ļaunumu uz kalniem!
54321 Viņi visi ir miruši! Treškārt, vairāku atslēgvārdu skaidrojums C / C ++ _declspec __stdcall Ārējais
"C" (DLLEXPORT) eksports no DLL, izmantojot __declspec (dllexport). </s.str<<endl; </s.i<<endl;
|