一,创建C++ DLL项目
修改 CPPTest.cpp 内容为: // 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
二,创建C#测试项目
修改Program 内容为: 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;
}
}
} 请留意以上介个DllImportAttribute标记的方法。 运行结果: 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! 三,关于C/C++中几个关键字的说明 _declspec __stdcall extern
"C" (dllexport) 使用 __declspec(dllexport) 从 DLL 导出
</s.str<<endl;
</s.i<<endl;
|