|
Primeiro, crie um projeto DLL em C++
Modifique CPPTest.cpp para dizer: CPPTest.cpp : Define o ponto de entrada para a aplicação DLL.
// #include "stdafx.h" #include #ifdef _MANAGED #pragma conseguiu (empurrar, sair) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReservado
)
{ retorne TRUE;
} externo "C"
{ struct TestStruct
{ int i; car* str; }; _declspec(dllexport) size_t __stdcall GetStringLength(char* & str)
{ devolver strlen(strlen);
} _declspec(dllexport) int __stdcall AddTwoNumber(const int a,const int b)
{ retorne a+b;
} _declspec(dllexport) void __stdcall StructTest(TestStruct& s)
{ usando namespace std; cout<<s.i<<endl; cout<<s.str<<endl; s.i=54321; s.str="Eles estão todos mortos!";
}
} #ifdef _MANAGED #pragma gerenciou (pop) #endif
2. Criar um projeto de teste em C#
Modificar o conteúdo do Programa para: usando o Sistema; usando System.Collections.Generic; usando System.Text; usando System.Runtime.InteropServices; namespace ConsoleApplicationTestCSharp
{ Programa da turma
{ [DllImport("CPPTest.dll")] static extern int GetStringLength(ref string str); [DllImport("CPPTest.dll")] extern estático int AddTwoNumber(int a, int b); [DllImport("CPPTest.dll")] vazio externo estático StructTest (ref TestStruct s); Static void Main(string[] args)
{ string testString = "HAHA! Sou uma corda de teste"; 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 = "Vá atirar nos males nas montanhas!"; StructTest (ref s); Console.WriteLine(s.i); Console.WriteLine(s.str); Console.ReadKey();
} [StructLayout(LayoutKind.Sequential)] estrutura pública TestStruct
{ público int i; força pública de cordas;
}
}
} Note a tag DllImportAttribute acimamétodo。 Resultado da corrida: comprimento(C++)=24 comprimento(C#)=24 a+b(C++)=1010 a+b(C#)=1010
12345 Vá atirar nos males nas montanhas!
54321 Todos estão mortos! Terceiro, uma explicação de várias palavras-chave em C/C++ _declspec __stdcall Externo
"C" (dllexport) exporta da DLL usando __declspec (dllexport). </s.str<<endl; </s.i<<endl;
|