|
まず、C++ DLLプロジェクトを作成します
CPPTest.cppを次のように修正してください: CPPTest.cpp : DLLアプリケーションのエントリーポイントを定義します。
// #include 「stdafx.h」 #include #ifdef _MANAGED #pragma うまくやった(押し、離れた) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call、 LPVOID lpReserved
)
{ TRUE を返します。
} 外部「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)
{ 返すA+B;
} _declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{ 名前空間STDの使用; Cout<<s.i<<endl; Cout<<S.Str<<endl; s.i=54321; s.str=「みんな死んでる!」;
}
} #ifdef _MANAGED #pragma 管理(ポップ) #endif
2. C#テストプロジェクトの作成
プログラム内容を以下に修正する: Systemを使い、 System.Collections.Genericを使い、 System.Textを使い、 System.Runtime.InteropServicesを使い、 namespace ConsoleApplicationTestCSharp
{ クラスプログラム
{ [DllImport("CPPTest.dll")] static extern int GetStringLength(ref string str); [DllImport("CPPTest.dll")] static extern int AddTwoNumber(int a, int b); [DllImport("CPPTest.dll")] 静的外部虚無 StructTest(参照 TestStruct s); static void Main(string[] args)
{ string testString = 「はは! 私はテストストリングです」と述べています。 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 = 新しいTestStruct(); s.i = 12345; s.str = 「ムタンの悪を撃ちに行け!」; StructTest(参考文献); Console.WriteLine(s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] パブリック構造体テストStruct
{ 公共情報I; パブリックストリングストレーション;
}
}
} 上記のDllImportAttributeタグにご注意ください方式。 ラン結果: length(C++)=24 長さ(C#)=24 a+b(C++)=10¹⁵ a+b(C#)=1010
12345 山の上の悪を撃ちに行け!
54321 みんな死んだ! 第三に、C/C++のいくつかのキーワードの説明 _declspec __stdcall エクスターン
「C」 (dllexport)は__declspec(dllexport)を使ってDLLからエクスポートされます。 </s.str<<endl; </s.i<<endl;
|