零,关于C++/CLR:
如果需要用到C++调用C#的东西的话,可以使用C++/CLR。这个算是对C++的扩展,不属于标准C++的东西。
一,一些基础的使用:
以VS2012为例,在project->properties->General->Common Language Runtime Support中,选择"Common Language Runtime Support (/clr)",就可以在工程中使用C++/CLR的东西了。
比如写个C#的类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpDllTest { public class CSharpClassMiao { public CSharpClassMiao() { } ~ CSharpClassMiao() { } void printMiao() { Console.Write("Hallo Kaetzchen! \r\n"); } } }
然后把编译好的DLL扔到C++的工程里,C++部分的代码如下:
#include < vcclr.h > #include <iostream> #using <../debug/CSharpDllTest.dll> using namespace std; using namespace CSharpDllTest; int _tmain(int argc, _TCHAR* argv[]) { CSharpClassMiao^ miao = gcnew CSharpClassMiao(); miao->printMiao(); }
这样就可以了。
但是gcnew出来的东西是属于托管的内容,什么时候留着什么时候删掉全看GC的心情。如果不放心怕被回收掉的话可以使用gcroot<T>,然后把它放到类的成员变量里。
这个原理相当于保存一个该对象的引用,只有引用计数大于0,GC就不会回收它了。
个人喜欢把C#类用C++封装一层。
例如:
class CppClassMiao { public: CppClassMiao() { m_instance = gcnew CSharpClassMiao(); } ~CppClassMiao() { //销毁的时候m_instance也就消失了,剩下的交给GC就好。 } private: gcroot<CSharpClassMiao^> m_instance; };
二,关于类型转换:
需要用到C#的Marshal类。
C++转C#:
参考:https://msdn.microsoft.com/zh-cn/library/ms146632%28v=vs.110%29.aspx
C#转C++:
参考:https://msdn.microsoft.com/zh-cn/library/ms146626%28v=vs.110%29.aspx
int testLen = 1024 * 1024 * 100; //这个是给C#用的字符数组了 array<unsigned char>^ ay = gcnew array<unsigned char>(testLen); //C++用的 char* ch = new char[testLen]; // ... // ... System::IntPtr^ ptr = gcnew System::IntPtr(ch); //把C++数组的东西赋值到C#里 System::Runtime::InteropServices::Marshal::Copy(*ptr, ay, 0, testLen); //把C#数组里的东西赋值给C++数组 System::Runtime::InteropServices::Marshal::Copy(ay, 0, *ptr, testLen);