|
Po pierwsze, stwórz projekt DLL w C++
Zmodyfikuj CPPTest.cpp, aby przeczytać: CPPTest.cpp : Definiuje punkt wejścia dla aplikacji DLL.
// #include "stdafx.h" #include #ifdef _MANAGED #pragma opanowany (pchnięcie, zdejmowanie) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved
)
{ return TRUE;
} zewnętrzny "C"
{ struct TestStruct
{ int i; char* str; }; _declspec(dllexport) size_t __stdcall GetStringLength(char* & str)
{ powrót strlen(str);
} _declspec(dllexport) int __stdcall AddTwoNumber(const int a,const int b)
{ zwróć a+b;
} _declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{ używając przestrzeni nazw std; cout<<s.i<<endl; cout<<s.str<<endl; s.i=54321; s.str="Wszyscy nie żyją!";
}
} #ifdef _MANAGED #pragma zarządzany (pop) #endif
2. Stworzyć projekt testowy w C#
Zmodyfikuj zawartość programu tak: z wykorzystaniem System; używając System.Collections.Generic; używając System.Text; używając System.Runtime.InteropServices; przestrzeń nazw ConsoleApplicationTestCSharp
{ Program klasowy
{ [DllImport("CPPTest.dll")] static extern int GetStringLength (ref string str); [DllImport("CPPTest.dll")] statyczny extern intAddTwoNumber(int a, int b); [DllImport("CPPTest.dll")] statyczny zewnętrzny void StructTest(ref TestStruct s); static void Main (string[] args)
{ string testString = "HAHA! Jestem testową nicią"; 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 = nowy TestStruct(); s.i = 12345; s.str = "Idź strzelać do zła na górach!"; StructTest(ref s); Console.WriteLine(s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] public struct TestStruct
{ public int i; struna publiczna str;
}
}
} Zwróć uwagę na powyższy tag DllImportAttributemetoda。 Wynik biegu: długość(C++)=24 długość(C#)=24 a+b(C++)=1010 a+b(C#)=1010
12345 Idź strzelać do zła na górach!
54321 Wszyscy nie żyją! Po trzecie, wyjaśnienie kilku słów kluczowych w C/C++ _declspec __stdcall Zewnętrzne
"C" (dllexport) eksportuje z DLL za pomocą __declspec (dllexport). </s.str<<endl; </s.i<<endl;
|