|
First, create a C++ DLL project
Modify CPPTest.cpp to read: // CPPTest.cpp : Defines the entry point for the DLL application.
// #include "stdafx.h" #include #ifdef _MANAGED #pragma managed(push, off) #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)
{ return a+b;
} _declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{ using namespace std; cout<<s.i<<endl; cout<<s.str<<endl; s.i=54321; s.str="They are all dead!";
}
} #ifdef _MANAGED #pragma managed(pop) #endif
2. Create a C# test project
Modify the Program content to: using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace ConsoleApplicationTestCSharp
{ class Program
{ [DllImport("CPPTest.dll")] static extern int GetStringLength(ref string str); [DllImport("CPPTest.dll")] static extern int AddTwoNumber(int a, int b); [DllImport("CPPTest.dll")] static extern void StructTest(ref TestStruct s); static void Main(string[] args)
{ string testString = "HAHA! I am a test string"; 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 = new TestStruct(); s.i = 12345; s.str = "Go to shoot evils on moutains!"; StructTest(ref s); Console.WriteLine(s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] public struct TestStruct
{ public int i; public string str;
}
}
} Note the DllImportAttribute tag abovemethod。 Run result: length(C++)=24 length(C#)=24 a+b(C++)=1010 a+b(C#)=1010
12345 Go to shoot evils on moutains!
54321 They are all dead! Third, an explanation of several keywords in C/C++ _declspec __stdcall extern
"C" (dllexport) exports from the DLL using __declspec (dllexport). </s.str<<endl; </s.i<<endl;
|